如果你有俩个具有很多相同属性的JavaBean,而你又不想手动的用get()set()方法来COPY。这时候copyProperties()方法的作用就体现出来了。例如经常用到的和hibernate绑定的实体,和另一个实体属性值的copy
public class APDto { private String ssid; private String deviceMac; private String bssid; private String deviceNo; private String deviceModel; private String bandWidth; private String bandOpr; private String storeId; private String storeName; private String brandName; private String storeProvince; private String storeCity; private String storeAddress; private String storeField; private String storeMail; private String storePhone; private String storeContact; private String storeLongitude; private String storeLatitude; //get,set方法省略 }
@Entity @Table(name = "wx_ap", catalog = "db_freeradius") public class WeiXinAP extends BaseEntity implements java.io.Serializable { /** * */ private static final long serialVer sionUID = -227365820215202729L; private Long id; private Long hid; private String ssid; private String deviceMac; private String bssid; private Long deviceNo; private String deviceModel; private String bandWidth; private String bandOpr; private Integer storeId; private String storeName; private String brandName; private String storeProvince; private String storeCity; private String storeAddress; private String storeField; private String storeMail; private String storePhone; private String storeContact; private double storeLongitude; private double storeLatitude; private int status; @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "id", unique = true) //省略get,set方法 }
使用BeanUtils.copyProperties(apDto,weiXinAP);方法就能把weixinAP对应的属性值赋给apDto,而weixinAP多余的字段不会对它作任何处理。
(PS当有的字段为null属性时,使用此方法会出现问题。例如int型的null使用此方法后对应的字段会变为0,如果你之后的业务逻辑有用null判断的情况,就会出现问题,这时候需要你去重写他的方法对为null的情况进行修改,建议使用spring中的BeanUtils)