[英]ConfigurationProperties in nested classes
使用以下 yml
app:
a:
prop: aaa
b:
prop: bbb
@Component
public abstract class Common {
@Value("${prop}")
private String prop;
@ConfigurationProperties(prefix = "app.a")
@PropertySource("classpath:app.yml")
@Component
public static class A extends Common {
}
@ConfigurationProperties(prefix = "app.b")
@PropertySource("classpath:app.yml")
@Component
public static class B extends Common {
}
}
但是對於a
或b
,這兩個類具有相同的值。
我該如何解決這個問題?
我發現了問題。 簡單地。 yml
不適用於PropertySource
。
我仍然想相信我是錯的。
我將.yml
文件更改為properties
並嘗試使用此方法。
@PropertySource("classpath:/vendor.properties")
@EnableConfigurationProperties
public abstract class Common {
@Value("${prop}")
private String prop;
@ConfigurationProperties(prefix = "app.a")
@Component
public static class A extends Common {
}
@ConfigurationProperties(prefix = "app.b")
@Component
public static class B extends Common {
}
}
它奏效了。
您可以使用配置參數列表:
app:
props:
- key: a
value: aaa
- key: b
value: bbb
並在單獨的 bean 中以更復雜的方式檢索您的價值:
@ConfigurationProperties(prefix = "app")
public class CommonConfiguration {
List<Prop> props;
//Getters and setters
public Prop retreiveSpecificConfiguration(String className) {
//some kind of logic here
}
public static class Prop {
private String key, value;
//Getters and setters
}
}
將它注入您的 Common 類實現中:
@Autowired
CommonConfiguration config;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.