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

栏目: Java · 发布时间: 7年前

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

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


以上所述就是小编给大家介绍的《兼容 Spring Boot 1.x 和 2.x 配置类参数绑定的工具类 SpringBootBindUtil》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Agile Web Application Development with Yii 1.1 and PHP5

Agile Web Application Development with Yii 1.1 and PHP5

Jeffrey Winesett / Packt Publishing / 2010-08-27

In order to understand the framework in the context of a real-world application, we need to build something that will more closely resemble the types of applications web developers actually have to bu......一起来看看 《Agile Web Application Development with Yii 1.1 and PHP5》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具