当前位置: 移动技术网 > IT编程>开发语言>Java > 兼容Spring Boot 1.x和2.x配置类参数绑定的工具类SpringBootBindUtil

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

2019年07月19日  | 移动技术网IT编程  | 我要评论
为了让我提供的通用 mapper 的 boot-starter 同时兼容 spring boot 1.x 和 2.x,增加了这么一个工具类。 在 spring boot

为了让我提供的通用 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就能得到想要的配置类了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网