欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

兼容Spring Boot 1.x和2.x配置类参数绑定的工具类SpringBootBindUtil

时间:2021-02-16 10:41:43|栏目:JAVA代码|点击:

为了让我提供的通用 Mapper 的 boot-starter 同时兼容 Spring Boot 1.x 和 2.x,增加了这么一个工具类。

在 Spring Boot 中,能够直接注入 XXProperties 类的地方不需要使用这个工具类。

但是在Spring 的接口和启动流程设计中,有些情况下只能通过EnvironmentAware接口得到Environment对象,此时你想得到 XXProperties 类没有更好的办法。

也许有人直接从Environment 对象中遍历获取所有的配置信息,但是有一个无法完美解决的问题就是relax 值,例如first-namefirstName, FIRST_NAME都可以代表同一个参数,在自己代码中很难处理这种情况。

通用 Mapper 在兼容两者过程中遇到过很多 BUG,这一次通过一个工具类解决了这个问题。

在 Spring Boot 1.x 中,可以通过下面代码绑定参数到对象:

try {
  RelaxedPropertyResolver resolver = new RelaxedPropertyResolver(environment);
  Map<String, Object> properties = resolver.getSubProperties("");
  //targetClass 目标类型,例如 MapperProperties
  T target = targetClass.newInstance();
  RelaxedDataBinder binder = new RelaxedDataBinder(target, prefix);
  binder.bind(new MutablePropertyValues(properties));
  return target;
} catch (Exception e) {
  throw new RuntimeException(e);
}

Spring Boot 2.x 中,绑定更简单,如下:

Binder binder = Binder.get(environment);
return binder.bind(prefix, targetClass).get();

上面这两段代码也是最近才找到,要不然这个功能会出现的更早。

由于上面的两处代码都在 spring-boot.jar 中,因此编译时不能同时依赖两个不同的版本,而且为了方便以后项目依赖从 1.x 升级到 2.x,因此针对上面两处代码全部使用反射实现。

源码地址:https://github.com/abel533/mapper-boot-starter/blob/master/mapper-spring-boot-autoconfigure/src/main/java/tk/mybatis/spring/mapper/SpringBootBindUtil.java

简单用法如下:

MapperProperties mapperProperties = SpringBootBindUtil.bind(
    environment, 
    MapperProperties.class, 
    MapperProperties.PREFIX);

至此通过environment就能得到想要的配置类了。

总结

上一篇:Java基于swing实现的弹球游戏代码

栏    目:JAVA代码

下一篇:详解Spring Boot 2.0.2+Ajax解决跨域请求的问题

本文标题:兼容Spring Boot 1.x和2.x配置类参数绑定的工具类SpringBootBindUtil

本文地址:http://www.codeinn.net/misctech/63987.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有