Spring BeanUtils属性copy

2020-08-26 10:29:00 浏览数 (1)

maven依赖

代码语言:javascript复制
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>5.0.9.RELEASE</version>
</dependency>

属性copy Demo

代码语言:javascript复制
public class BeanUtilsTest {

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class DO{
        private Bean bean;
        private String name;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class DTO{
        private Bean bean;
        private String age;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Bean{
        private String uid;
    }

    public static void main(String[] args) {
        Bean bean = new Bean("123");
        DO aDo = new DO(bean,"zhangsan");
        DTO aTo = new DTO();
        BeanUtils.copyProperties(aDo, aTo);
        // out => BeanUtilsTest.DTO(bean=BeanUtilsTest.Bean(uid=123), age=null)
        System.out.println(aTo);
        // 测试是否是浅拷贝
        bean.setUid("456");
        // out => BeanUtilsTest.DTO(bean=BeanUtilsTest.Bean(uid=456), age=null)
        System.out.println(aTo);
        // 结论: Spring BeanUtils 拷贝是浅拷贝
    }
}

0 人点赞