![](/img/trans.png)
[英]How to use @ConfigurationProperties annotation in Spring Boot
[英]How to use @ConstructorBinding and @PropertySource together with @ConfigurationProperties with in Spring Boot 2.2.4?
我是 Spring Boot 的新手。 目前,我正在嘗試創建一個 POJO 類( SystemProperties.class )來讀取屬性文件中的值( parameter.properties與 application.properties 分開但仍在同一目錄 /src/main/resources 下。當我我在類中使用 @ConstructorBinding 以使其不可變。
- @ConstructorBinding 需要與@EnableConfigurationProperties 或@ConfigurationPropertiesScan 一起使用。
- @ConfigurationPropertiesScan 將忽略使用 @PropertySource 指定外部時需要的 @Configuration 注釋
*.properties 文件。
A) SystemProperties.class
@Configuration
@PropertySource("classpath:parameter.properties")
@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {
private final String test;
public SystemProperties (
String test) {
this.test = test;
}
public String getTest() {
return test;
}
B) 參數.properties
abc.test=text1
我試圖刪除@PropertySource 注釋,但無法檢索該值,除非它來自 application.properties。 任何幫助是極大的贊賞!
解決這個問題的方法是將類分成具有兩個不同關注點的兩個類。 使用這種解決方案,您可以保留您創建的 SystemProperties 類,並另外添加另一個類,僅用於加載屬性文件參數,使它們可用於您的應用程序。
解決方法如下:
@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {
private final String test;
public SystemProperties(
String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
請注意,我省略了@Configuration
和@PropertySource
注釋。
@Configuration
@PropertySource("classpath:parameter.properties")
public class PropertySourceLoader {
}
請注意,我只是在一個新類上添加了此注釋,該類僅用於加載屬性文件。
最后,您可以在主應用程序類上添加@ConfigurationPropertiesScan
以啟用屬性映射機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.