SpringBoot @ConfigurationProperties實現型別安全的配置(基於properties) 使用過程及碰到的問題解決
前言:
使用@ConfigurationProperties將properties屬性和一個Bean及其屬性關聯,可以方便的實現型別安全的配置,比@Value需要注入很多次方便很多。
這裡記錄@ConfigurationProperties使用過程中碰到的問題及解決方案
碰到的問題:
- SpringBoot 1.5以上版本@ConfigurationProperties取消location註解
- SpringBoot Configuration Annotation Processor not found in classpath錯誤
- Re-run Spring Boot Configuration Annotation Processor to update generated metadata警告
注:解決方案在文章最後
使用過程:
目的:通過使用@ConfigurationProperties註解,及相應的Bean,實現型別安全的配置
1、首先在resources目錄下新建一個test.properties檔案,具體目錄結構如下:
test.properties內容為:
author.name = xafxa
author.age = 18
注:相同屬性字首必須一樣,如這裡的author,格式為 xxx.xxxx
2、建立相應的Bean及其屬性,具體目錄結構如下:
AuthorSettingsBean內容如下:
@Component //標記本類為一個Bean,可以使用@Autowried注入 @PropertySource("classpath:test.properties") //SpringBoot 1.5以上版本取消 @ConfigurationProperties中location屬性,這裡用@PropertySource代替 @ConfigurationProperties(prefix = "author") //@ConfigurationProperties中填寫需要用到 prefix public class AuthorSettingsBean { private String name; //這裡的屬性內容對應 test.properties中author.name, author.age配置 private String age; public String getName(){ return this.name; } public void setName(String name){ this.name = name; } public String getAge(){ return this.age; } public void setAge(String age){ this.age = age; } }
3、使用,這裡新建一個TestController,在TestController中獲取我們先前配置的author資訊
目錄結構如下:
TestController.java內容如下:
@RestController @EnableConfigurationProperties(AuthorSettingsBean.class) //重要,啟用繫結的Bean public class TestController { @Autowired //將繫結的某個bean自動注入 private AuthorSettingsBean author; @RequestMapping("/test") public String test(){ return "author info: name: " + author.getName() + " age: " + author.getAge(); } }
4、驗證,在瀏覽中輸入 http://localhost:9090/test (注:這裡的9090埠是我的測試工程配置,預設為8080),檢視結果如下:
以上就是@CofigurationProperties的使用過程,下面來解決文章開頭提到的問題
解決碰到的問題:
1、Springboot 1.5以上版本@ConfigurationProperties取消location的替代方案,這裡做具體流程簡述,詳細過程可以看上面使用過程。
a、在相應Bean上寫 @PropertySource註解,寫明classpath,如:
@PropertySource("classpath:test.properties")
b、使用的時候,如在例子中的TestController,寫@EnableConfigurationProperties 啟用相應的Bean,如
@EnableConfigurationProperties(AuthorSettingsBean.class)
c、使用@Autowired自動注入
2、Spring Boot Configuration Annotation Processor not found in classpath錯誤:
需要在pom.xml引入註解依賴,具體如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
3、Re-run警告:
這個目前還沒找到合適的解決方案,不過只是一個提示,影響不大
嘗試過的辦法:
重啟Idea、rebuild 失敗
參照如下連結:
https://stackoverflow.com/questions/33483697/re-run-spring-boot-configuration-annotation-processor-to-update-generated-metada 沒具體解決。