How to Exclude Null Values When Using Spring Framework's BeanUtils to Copy Properties?

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

Related Questions

⦿How to Obtain an InputStream Using RestTemplate Instead of URL in Java?

Learn how to retrieve an InputStream with RestTemplate in Java replacing the traditional URL class usage. Optimize your HTTP calls efficiently.

⦿How to Resolve the 'Cannot call sendError() after the response has been committed' Exception in Tomcat?

Learn how to troubleshoot and fix the Cannot call sendError after the response has been committed exception in Apache Tomcat with detailed solutions and code examples.

⦿What is the Best IDE for Developing Swing Applications?

Discover the best IDEs for developing Java Swing applications including userfriendly options like IntelliJ IDEA and Eclipse.

⦿How to Use Toolbar with Fragments in Android ViewPager

Learn how to implement Toolbar with Fragments in Android ViewPager solve common issues and enhance your apps UI.

⦿How to Reverse Item Order in LinearLayoutManager Without Stacking from Bottom

Learn how to reverse RecyclerView items using LinearLayoutManager while ensuring items stack from the top instead of the bottom.

⦿How to Retrieve a Spring Bean Inside a Servlet Filter

Discover how to access Spring beans from a servlet filter in Java effectively with clear examples and solutions.

⦿How to Resolve "Unable to Find Instrumentation Info for: ComponentInfo{ }" Error in Android Espresso Tests?

Learn how to troubleshoot the Unable to find instrumentation info error in Android Espresso Testing with detailed solutions common mistakes and code snippets.

⦿How to Start a Spring Boot Application in Docker with a Specific Profile

Learn how to run your Spring Boot app in Docker with an active profile using proper Dockerfile configuration and common troubleshooting tips.

⦿How to Check the Status of a Java JDBC Database Connection?

Learn how to verify if your Java JDBC database connection is still active including checks and code examples.

⦿How to Fix 'Received Fatal Alert: Protocol Version' Error in Maven?

Resolve Received fatal alert protocolversion error in Maven when using an older Java version. Learn how to update your environment correctly.

© Copyright 2025 - CodingTechRoom.com