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

作者:isea533 时间:2023-11-03 05:35:06 

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

来源:https://blog.csdn.net/isea533/article/details/79121981

标签:spring,boot,springbootbindutil,工具类
0
投稿

猜你喜欢

  • Java Swing JFrame窗口的实现

    2021-11-30 12:03:37
  • Android中检查、设置默认程序详解

    2021-08-25 14:14:21
  • Java AWT中常用的三种布局管理器详解

    2023-02-11 20:55:25
  • init output stream初始化输出流源码分析

    2023-01-08 09:53:20
  • Flutter生命周期超详细讲解

    2022-12-31 04:45:57
  • Java static关键字详细解析

    2021-08-12 00:40:23
  • Android实现在一个activity中添加多个listview的方法

    2023-10-13 14:41:22
  • Android APK使用Debug签名重新打包 Eclipse更改默认Debug签名

    2022-03-07 13:27:12
  • SpringBoot+netty-socketio实现服务器端消息推送

    2023-11-15 06:14:31
  • 从零实现一个简单的Spring Bean容器的代码案例

    2022-07-24 11:42:16
  • Java常用HASH算法总结【经典实例】

    2023-04-26 00:34:55
  • Java interrupt()方法使用实例介绍

    2022-05-04 11:09:35
  • 带你一文了解C#中的Expression

    2023-04-20 04:37:57
  • Android使用gallery和imageSwitch制作可左右循环滑动的图片浏览器

    2021-08-31 22:49:45
  • Java并发系列之AbstractQueuedSynchronizer源码分析(共享模式)

    2022-06-03 13:39:58
  • Java超详细梳理IO流的使用方法上

    2023-07-21 16:31:25
  • C# 索引器的使用教程

    2022-08-25 05:11:59
  • Java多线程 volatile关键字详解

    2023-07-16 02:13:31
  • 让C# Excel导入导出 支持不同版本Office

    2023-01-11 05:30:53
  • python、java等哪一门编程语言适合人工智能?

    2021-06-04 03:22:53
  • asp之家 软件编程 m.aspxhome.com