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一致的情况,因此在使用阶段需要注意相同属性名的问题。

经验分享 程序员 微信小程序 职场和发展