如何使用springframework BeanUtils copyProperties忽略空值?

我想知道如何使用Spring Framework将属性从Object Source复制到Object Dest忽略null值。

我实际上使用Apache beanutils,使用此代码

beanUtils.setExcludeNulls(true); beanUtils.copyProperties(dest, source); 

去做吧。 但现在我需要使用Spring。

有帮助吗?

多谢

您可以创建自己的方法来复制属性,同时忽略空值。

 public static String[] getNullPropertyNames (Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set emptyNames = new HashSet(); for(java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null) emptyNames.add(pd.getName()); } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } // then use Spring BeanUtils to copy and ignore null public static void myCopyProperties(Object src, Object target) { BeanUtils.copyProperties(src, target, getNullPropertyNames(src)) } 

来自alfredx post的 Java 8版本的getNullPropertyNames方法:

 public static String[] getNullPropertyNames(Object source) { final BeanWrapper wrappedSource = new BeanWrapperImpl(source); return Stream.of(wrappedSource.getPropertyDescriptors()) .map(FeatureDescriptor::getName) .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null) .toArray(String[]::new); } 

SpringBeans.xml

          
  1. 创建一个java Bean,

    公共类HelloWorld {

     private String name; private String gender; public void printHello() { System.out.println("Spring 3 : Hello ! " + name + " -> gender -> " + gender); } 

    // Getters和Setters

  2. 创建要测试的主类

    public class App {public static void main(String [] args){ApplicationContext context = new ClassPathXmlApplicationContext(“SpringBeans.xml”);

      HelloWorld source = (HelloWorld) context.getBean("source"); HelloWorld target = (HelloWorld) context.getBean("target"); String[] nullPropertyNames = getNullPropertyNames(target); BeanUtils.copyProperties(target,source,nullPropertyNames); source.printHello(); } public static String[] getNullPropertyNames(Object source) { final BeanWrapper wrappedSource = new BeanWrapperImpl(source); return Stream.of(wrappedSource.getPropertyDescriptors()) .map(FeatureDescriptor::getName) .filter(propertyName -> wrappedSource.getPropertyValue(propertyName) == null) .toArray(String[]::new); } 

    }

我建议你使用ModelMapper。

这是一个解决您疑问的示例代码。

  ModelMapper modelMapper = new ModelMapper(); modelMapper.getConfiguration().setSkipNullEnabled(true).setMatchingStrategy(MatchingStrategies.STRICT); Company a = new Company(); a.setId(123l); Company b = new Company(); b.setId(456l); b.setName("ABC"); modelMapper.map(a, b); System.out.println("->" + b.getName()); 

它应该打印B值。 但是,如果设置“A”名称,则结果为“A”值的打印。

秘诀是将SkipNullEnabled的值更改为true。

ModelMapper

ModelMapper MVN