How to ignore null values using springframework BeanUtils copyProperties?

后端 未结 6 1328
悲哀的现实
悲哀的现实 2020-12-01 00:09

I would like to know how to copy the properties from an Object Source to an Object Dest ignoring null values​​ using Spring Framework.

I actually use Apache beanutil

6条回答
  •  天涯浪人
    2020-12-01 00:43

    SpringBeans.xml

    
    
        
            
            
        
    
        
            
        
    
    
    
    1. Create a java Bean,

      public class HelloWorld {
          private String name;
          private String gender;
      
          public void printHello() {
              System.out.println("Spring 3 : Hello ! " + name + "    -> gender      -> " + gender);
          }
      
          //Getters and Setters
      }
      
    2. Create Main Class to test

      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);
          }
      }
      

提交回复
热议问题