Question
How can I copy properties between two objects while ignoring null values using Spring Framework's BeanUtils?
// Example of using Spring BeanUtils
import org.springframework.beans.BeanUtils;
public void copyPropertiesIgnoringNulls(Object source, Object dest) {
BeanUtils.copyProperties(source, dest, getNullPropertyNames(source));
}
private String[] getNullPropertyNames(Object source) {
BeanWrapper beanWrapper = new BeanWrapperImpl(source);
return Arrays.stream(beanWrapper.getPropertyDescriptors())
.filter(pd -> beanWrapper.getPropertyValue(pd.getName()) == null)
.map(PropertyDescriptor::getName)
.toArray(String[]::new);
}
Answer
In the Spring Framework, the BeanUtils class provides a straightforward way to copy properties from one Java object to another. However, by default, it does not ignore null values. To achieve this, we can create utility methods to identify null properties and exclude them during the copying process.
// Example of using Spring BeanUtils to copy properties while ignoring nulls
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeanUtils;
import java.beans.PropertyDescriptor;
import java.util.Arrays;
public class PropertyCopyUtils {
public static void copyPropertiesIgnoringNulls(Object source, Object dest) {
BeanUtils.copyProperties(source, dest, getNullPropertyNames(source));
}
private static String[] getNullPropertyNames(Object source) {
BeanWrapper beanWrapper = new BeanWrapperImpl(source);
return Arrays.stream(beanWrapper.getPropertyDescriptors())
.filter(pd -> beanWrapper.getPropertyValue(pd.getName()) == null)
.map(PropertyDescriptor::getName)
.toArray(String[]::new);
}
}
Causes
- Using BeanUtils.copyProperties without null checks results in overwriting non-null properties with null values.
- The default implementation does not provide an option to directly exclude null values.
Solutions
- Create a method to find and obtain the names of all null properties from the source object.
- Use the obtained property names to inform BeanUtils about which properties should not be copied.
Common Mistakes
Mistake: Not using the correct method to filter null properties from the source object.
Solution: Ensure to create a helper method that retrieves null property names before copying properties.
Mistake: Trying to copy properties directly without handling null cases.
Solution: Always use the method designed to exclude null property names when calling BeanUtils.copyProperties.
Helpers
- Spring Framework
- BeanUtils
- copy properties
- ignore null values
- Java
- object mapping
- Spring BeanUtils