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

转载于:https://www.cnblogs.com/java-jun-world2099/articles/11023541.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值