복붙노트

[SPRING] springframework BeanUtils copyProperties를 사용하여 null 값을 무시하는 방법?

SPRING

springframework BeanUtils copyProperties를 사용하여 null 값을 무시하는 방법?

개체 소스의 속성을 Spring Framework를 사용하여 null 값을 무시하는 개체 대상에 복사하는 방법을 알고 싶습니다.

실제로이 코드와 함께 Apache beanutils를 사용합니다.

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

그것을하기 위해. 하지만 지금 나는 봄을 사용해야합니다.

어떤 도움이 필요합니까?

정말 고마워

해결법

  1. ==============================

    1.Null 값을 무시하면서 고유 한 메서드를 만들어 속성을 복사 할 수 있습니다.

    Null 값을 무시하면서 고유 한 메서드를 만들어 속성을 복사 할 수 있습니다.

    public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
    
        Set<String> emptyNames = new HashSet<String>();
        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))
    }
    
  2. ==============================

    2.alfredx의 게시물에서 getNullPropertyNames 메소드의 Java 8 버전 :

    alfredx의 게시물에서 getNullPropertyNames 메소드의 Java 8 버전 :

    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);
    }
    
  3. ==============================

    3.SpringBeans.xml

    SpringBeans.xml

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
        <bean id="source" class="com.core.HelloWorld">
            <property name="name" value="Source" />
            <property name="gender" value="Male" />
        </bean>
    
        <bean id="target" class="com.core.HelloWorld">
            <property name="name" value="Target" />
        </bean>
    
    </beans>
    
  4. ==============================

    4.ModelMapper를 사용하는 것이 좋습니다.

    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 MAVEN

  5. from https://stackoverflow.com/questions/19737626/how-to-ignore-null-values-using-springframework-beanutils-copyproperties by cc-by-sa and MIT license