溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

兼容Spring Boot 1.x和2.x配置類參數(shù)綁定的工具類SpringBootBindUtil

發(fā)布時間:2020-09-04 10:49:19 來源:腳本之家 閱讀:149 作者:isea533 欄目:編程語言

為了讓我提供的通用 Mapper 的 boot-starter 同時兼容 Spring Boot 1.x 和 2.x,增加了這么一個工具類。

在 Spring Boot 中,能夠直接注入 XXProperties 類的地方不需要使用這個工具類。

但是在Spring 的接口和啟動流程設(shè)計中,有些情況下只能通過EnvironmentAware接口得到Environment對象,此時你想得到 XXProperties 類沒有更好的辦法。

也許有人直接從Environment 對象中遍歷獲取所有的配置信息,但是有一個無法完美解決的問題就是relax 值,例如first-name,firstName, FIRST_NAME都可以代表同一個參數(shù),在自己代碼中很難處理這種情況。

通用 Mapper 在兼容兩者過程中遇到過很多 BUG,這一次通過一個工具類解決了這個問題。

在 Spring Boot 1.x 中,可以通過下面代碼綁定參數(shù)到對象:

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();

上面這兩段代碼也是最近才找到,要不然這個功能會出現(xiàn)的更早。

由于上面的兩處代碼都在 spring-boot.jar 中,因此編譯時不能同時依賴兩個不同的版本,而且為了方便以后項目依賴從 1.x 升級到 2.x,因此針對上面兩處代碼全部使用反射實現(xiàn)。

源碼地址: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就能得到想要的配置類了。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對億速云的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI