一探Spring中BeanUtils的copyProperties方法

本文探讨了Spring中BeanUtils.copyProperties方法的工作原理,指出成功复制属性需满足的三个条件:属性名相同,源对象需有get方法,目标对象需有set方法且类型匹配。即使是内部类或泛型不同,只要运行时类型兼容,仍可进行复制。参考自www.jianshu.com/p/357b55852efc。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private static void copyProperties(Object source, Object target, @Nullable Class<?> editable, @Nullable String... ignoreProperties) throws BeansException {
        Assert.notNull(source, "Source must not be null");
        Assert.notNull(target, "Target must not be null");
        Class<?> actualEditable = target.getClass();
        if (editable != null) {
            if (!editable.isInstance(target)) {
                throw new IllegalArgumentException("Target class [" + target.getClass().getName() + "] not assignable to Editable class [" + editable.getName() + "]");
            }

            actualEditable = editable;
        }

	//获取目标对象的各属性信息
        PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
        List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
        PropertyDescriptor[] var7 = targetPds;
        int var8 = targetPds.length;

        //遍历各属性
        for(int var9 = 0; var9 < var8; ++var9) {
            PropertyDescriptor targetPd = var7[var9];
	//获取目标对象该属性的写方法,即set方法
            Method writeMethod = targetPd.getWriteMethod();
	//判断该属性是否在不被copy的属性集合中
            if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
		//根据目标对象的属性名称,获取源对象的该属性信息
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
			 //获取源对象的该属性的读方法,即get方法
                    Method readMethod = sourcePd.getReadMethod();
			 //判断目标对象的set方法所需的参数类型和源对象get方法的返回类型是否一致
                    if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
			    //如果源对象的get方法不包含public修饰符,将该方法修改为可以通过反射外部访问
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                readMethod.setAccessible(true);
                            }
						
			    //通过反射获取源对象该属性的值
                            Object value = readMethod.invoke(source);
			    //如果目标对象的set方法不包含public修饰符,将该方法修改为可以通过反射外部访问
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
							
			    //通过反射将值写入目标对象
                            writeMethod.invoke(target, value);
                        } catch (Throwable var15) {
                            throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
                        }
                    }
                }
            }
        }

    }

通过copyProperties方法的源代码可以看出,实现此功能有三个必须条件:
1.需要复制的属性名要相同;
2.对于要复制的属性,源对象必须有get方法,目标对象必须有set方法;
3.目标对象的set方法所需的参数类型和源对象get方法的返回类型保持一致。

下面贴上测试类和测试代码:

被复制的类

public class CopyTest1 {

    private String outStr;
    private CopyTest1.Inner inner;
    private List<Integer> num;

    public static class Inner {
        public String inStr;
    }

    public String getOutStr() {
        return outStr;
    }

    public void setOutStr(String outStr) {
        this.outStr = outStr;
    }

    public Inner getInner() {
        return inner;
    }

    public void setInner(Inner inner) {
        this.inner = inner;
    }

    public List<Integer> getNum() {
        return num;
    }

    public void setNum(List<Integer> num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "CopyTest1{" +
                "outStr='" + outStr + '\'' +
                ", inner=" + inner +
                ", num=" + num +
                '}';
    }

目标类

public class CopyTest2 {

    private String outStr;
    private CopyTest2.Inner inner;
    private List<String> num;

    public static class Inner {
        public String inStr;
    }

    public String getOutStr() {
        return outStr;
    }

    public void setOutStr(String outStr) {
        this.outStr = outStr;
    }

    public Inner getInner() {
        return inner;
    }

    public void setInner(Inner inner) {
        this.inner = inner;
    }

    public List<String> getNum() {
        return num;
    }

    public void setNum(List<String> num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "CopyTest2{" +
                "outStr='" + outStr + '\'' +
                ", inner=" + inner +
                ", num=" + num +
                '}';
    }
}

测试方法

public static void main(String[] args) {
        CopyTest1 test1 = new CopyTest1();
        test1.setOutStr("hahahaha");
        List<Integer> num = new ArrayList();
        num.add(1);
        test1.setNum(num);
        CopyTest1.Inner inner = new CopyTest1.Inner();
        inner.inStr = "hohohoho";
        test1.setInner(inner);

        System.out.println(test1.toString());
        CopyTest2 test2 = new CopyTest2();
        BeanUtils.copyProperties(test1, test2);
        System.out.println(test2.toString());
    }

从debug的效果看出属于两个类中的内部类,即使类名和属性名都相同相同,仍然不会复制,因为目标对象的set方法所需的参数类型和源对象get方法的返回类型是不一致,违反了条件3。因此,内部类需要单独使用copyProperties方法,复制一遍属性。

源对象中的list泛型为Integer,而目标对象中list的泛型为String,但是泛型只是编译期起约束作用,运行期可以看出set的参数类型和get的返回类型都是java.util.List,并无约束,因此也可以实现复制。

本文参考:www.jianshu.com/p/357b55852efc

### Java实现大学生兼职平台的主要接口类型 在Java中构建大学生兼职平台时,主要依赖于Spring框架中的子项目(如Spring MVC、Spring Data JPA),以及MyBatis或Hibernate等ORM工具来完成业务逻辑层和持久化层的功能开发。以下是几个核心模块所对应的RESTful API接口定义: #### 1.用户认证授权相关接口 - **注册接口** - 描述:提供给未注册的新用户提供填写个人信息并加入系统的入口。 - URL路径:`POST /api/auth/signup` - 输入参数: `username`, `password`, `email` 等基本信息字段[^1]. - **登录接口** - 描述:验证用户的凭证合法性,并颁发访问令牌以便后续调用受保护资源。 - URL路径:`POST /api/auth/signin` - 输入参数: 用户名(`username`) 及 密码(`password`) - 输出结果: JSON Web Token (JWT)[^2]. #### 2.职位管理服务端点 - **新增职位公告** - 描述:允许雇主方录入新的招聘需求条目到平台上公开招募人才。 - URL路径:`POST /api/jobs/create` - 请求体样例: ```json { "title":"Web Developer Intern", "description":"Looking for an intern who can help us build web applications...", "salaryRange":[3000,5000], ... } ``` - 注解解释:[@RequestBody JobPostDto postDetails][^3] - **获取所有有效职位列表** - 描述:供浏览者查阅目前可应聘的所有开放性岗位摘要集合。 - URL路径:`GET /api/jobs/listActiveJobs` - 查询字符串示例:?pageNo=1&pageSize=10&sortField=title&orderType=ASC #### 3.求职申请处理流程APIs - **提交求职意向书** - 描述:准员工能够针对感兴趣的具体某项工作发起正式的求职请求。 - URL路径:`PUT /api/applications/{jobId}/applyNow` - 路径变量:{jobId}表示目标工作的唯一标识符。 - 表单数据可能包括简历附件上传等内容[^4]. - **追踪我的求职状态** - 描述:已递交过材料的学生可以随时查探自己候选进程的状态更改情况。 - URL路径:`GET /api/tracking/myApplicationStatuses` - 客户端需携带有效的身份证明token随同HTTP头一起传递过去。 #### 4.管理员后台控制台专属功能集锦 - **批量导入导出Excel文档** - 描述:简化大量数据的一次性迁移作业过程。 - URL路径:`POST /api/admin/bulkImportExport` - 支持CSV/XLSX格式解析与生成操作[^5]. - **设置全局配置参数** - 描述:调整站点运营期间的各项默认设定值比如每日最大在线人数限额之类的数值型属性。 - URL路径:`PATCH /api/settings/globalConfigurations` --- ```java @RestController @RequestMapping("/api/users") public class UserController { @PostMapping("/signup") public ResponseEntity<?> registerUser(@Valid @RequestBody SignupRequest signupReq){ // 实现省略... } } @Service class UserServiceImpl implements UserService{ private final UserRepository repo; public Boolean saveNewUser(SignupRequest req){ UserEntity entity=new UserEntity(); BeanUtils.copyProperties(req,entity); return this.repo.save(entity)!=null; } } ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值