What is the method for Bean copy in SpringBoot?

In Spring Boot, you can use the copyProperties() method of the BeanUtils class to copy beans. This method copies the property values of one JavaBean object to another JavaBean object. The specific usage method is as follows:

  1. Import the necessary dependencies.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-beanutils</artifactId>
</dependency>
  1. Use the copyProperties() method for copying Beans in the code.
import org.springframework.beans.BeanUtils;

public class MyClass {
    private String name;
    private int age;
    
    // 省略getter和setter方法
    
    public static void main(String[] args) {
        MyClass source = new MyClass();
        source.setName("John");
        source.setAge(25);
        
        MyClass target = new MyClass();
        BeanUtils.copyProperties(source, target);
        
        System.out.println(target.getName()); // 输出:John
        System.out.println(target.getAge()); // 输出:25
    }
}

In the example above, we used the BeanUtils.copyProperties(source, target) method to copy the property values from the source object to the target object. After copying, the target object’s name property has a value of “John” and the age property has a value of 25.

bannerAds