BeanUtils.copyProperties的用法

BeanUtils.copyProperties(source,target)有两个参数,用于将事件源的数据拷贝到目标源中。

但是BeanUtils有两个,一个是spring的,一个是apache的commons下的。用法一样,但是两者的区别在于:一个是将前者拷贝给后者,另一个是将后者拷贝给前面的。

public class Test{
    public static void main(String[] args) {
            Student studentOne  = new StudentOne("张三");
            Student studentTwo  = new StudentOne();
            //BeanUtils.copyProperties是将studentOne的数据拷贝给studentTwo
            BeanUtils.copyProperties(studentOne, studentTwo);
    }
}

如果两个类不一样时,只会拷贝属性一样的内容。

@Data
public class User {
    private Integer id;
    private String idCard;
    private String pwd;
    private String workUnit;
    private String name;
    private String sex;
}
@Data
public class Salary {
    private Integer id;

    private Integer userId;

    private String idCard;
}
@Data
public class UserSalaryDto{
    private Integer id;
    private String idCard;
    private String pwd;
    private String workUnit;
    private String name;
    private String sex;
    private Integer userId;
    private String idCard;
}
public class Test{
    public void test(UserSalaryDto userSalaryDto) {
            //BeanUtils.copyProperties是将studentOne的数据拷贝给studentTwo
            User user = new User();
            Salary salary = new Salary();
            BeanUtils.copyProperties(userSalaryDto, user);
            BeanUtils.copyProperties(userSalaryDto, salary);
    }
}

这时需要注意的是id属性应该为User的属性,salary的id获取的为User的id,会出现id与userId一致的情况,因此在使用阶段需要注意相同属性名的问题。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

黑白交織℡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值