本文主要介紹了spring boot配置排序依賴技巧,分享給大家,具體如下:
spring boot - 被錯誤使用的注解
我自己曾經在 spring boot 中集成通用 mapper 時,寫過下面的代碼:
1
2
3
4
5
|
@configuration @autoconfigureafter (mybatisconfig. class ) public class mybatismapperscannerconfig { //其他 } |
這種用法我參考的 mybatis-spring-boot-starter。
由于在我自己這個例子中可以良好的運行,因此我以為 @autoconfigureafter 真正起作用了,否則怎么不報錯呢。但是在很長一段時間內,好多人參考這種用法時經常報錯,這個配置沒有起到應有的作用。我還一直以為他們用的不對。
直到昨天我開始寫自己的 pagehelper-spring-boot-starter 時,我才發現,我自己一直以來都用錯了。在我自己例子中,之所以能行,完全是靠運氣。
spring boot 提供了很多新的注解,但是要注意這個包下面的所有注解:
1
|
org.springframework.boot.autoconfigure |
這個包下面常見的注解有:
- @autoconfigureafter
- @autoconfigurebefore
- @autoconfigureorder
- @autoconfigurationpackage
- @enableautoconfiguration
- @springbootapplication
前 3 個是不能在普通項目中使用的,這 3 個注解是特地用于 autoconfigure 類的項目,后面 3 個注解是可以用于我們自己項目中的。
autoconfigure 類項目
spring boot starter 提供了規范可以讓開發者提供自己的 starter,例如 spring 官方提供的:
- spring-boot-starter
- spring-boot-starter-activemq
- spring-boot-starter-cache
- 等等…
還有很多開源項目或公司提供的:
- modelmapper-spring-boot-starter
- hajdbc-spring-boot-starter
- camel-spring-boot-starter
- mybatis-spring-boot-starter
- 等等…
在 spring boot starter 開發規范中,項目中會有一個空的名為 xxx-spring-boot-starter 的項目,這個項目主要靠 pom.xml 將所有需要的依賴引入進來。同時項目還會有一個 xxx-spring-boot-autoconfigure 項目,這個項目主要寫帶 @configuration 注解的配置類,在這個類或者類中帶 @bean 的方法上,可以使用和順序有關的注解,也就是前面提到的自己不能使用的這部分注解。xxx-spring-boot-autoconfigure 就是這里提到的 autoconfigure 類項目。
上面的注解只在 autoconfigurationsorter 類中排序時用到了。被排序的這些類,都是通過 xxx-spring-boot-autoconfigure 項目中的 src/resources/meta-inf/spring.factories 配置文件獲取的,這個文件中的配置內容一般為:
1
2
3
|
# auto configure org.springframework.boot.autoconfigure.enableautoconfiguration=\ com.github.pagehelper.autoconfigure.pagehelperautoconfiguration |
spring boot 只會對從這個文件讀取的配置類進行排序。
但是你不要以為將自己的配置類也配置在 spring.factories 中就能實現排序,如果你的類被自己 spring boot 啟動類掃描到了,這個類的順序會優先于所有通過 spring.factories 讀取的配置類。所以當你的配置類對順序有要求時就會出錯。
通過 spring.factories 巧妙使用排序
如果你將自己的配置類放到特別的包下,不使用 spring boot 啟動類掃描。完全通過 spring.factories 讀取配置就可以實現這個目的。例如下圖的用法:
當使用上圖方式進行配置時,就可以完美的使用第一節中不可使用的注解,如果你想讓這個配置應用到更多的項目中,建議按照 spring-boot-starter 規范開發自己的 starter。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/isea533/article/details/53975720