<导航

Spring中提供的属性拷贝的方法BeanUtils.copyProperties

BeanUtils.copyProperties通过java反射将类中当前属性字段对应的内容复制到另外一个类中。

1. BeanUtils.copyProperties(Object source, Object target) throws BeansException {}
2.public static void copyProperties(Object source, Object target, String... ignoreProperties)
ignoreProperties可以是一组需要忽略复制的字符串
3.public static void copyProperties(Object source, Object target, Class<?> editable)
editable确定需要操作的目前对象类

案例:
1. 创建一个实体类
//lombok中的注解,省去添加settter和getter方法
@Data
public class Book {
    private String username;
    private String password;
    private String email;
    }


2. 创建被复制的实体类
//lombok中的注解,省去添加settter和getter方法
@Data
public class Book {
public class Book2 {
    private String username;
    private String password;
    private String email;
}

3. 测试
 public static void main(String[] args) {
        Book book = new Book();
        book.setEmail("abc@163.com");
        book.setPassword("123456");
        book.setUsername("happygiraffe");
        Book2 book2 = new Book2();
        //添加了忽略username属性的赋值
        BeanUtils.copyProperties(book,book2,"username");

        System.out.println(book.toString());
        System.out.println(book2.toString());
    }
 4. 打印结果:
 Book{username='happygiraffe', password='123456', email='abc@163.com'}
 Book2{username='null', password='123456', email='abc@163.com'}

注意:spring的BeanUtils.copyProperties 只拷贝属性类型和属性名都相同的属性。其中基础类型(int long short)和其包装类是可以互相拷贝的。

      spring的BeanUtils.copyProperties默认引用拷贝,如果需要对象拷贝 需要自定义。

 

 

 

 参考文章:

https://blog.csdn.net/m0_37779570/article/details/81094731

https://docs.spring.io/spring-framework/docs/2.5.x/api/org/springframework/beans/BeanUtils.html

posted @ 2019-06-14 15:31  字节悦动  阅读(7010)  评论(0编辑  收藏  举报