[英]How to read external properties based on value of local variable in Spring Boot?
假設我的 application.properties 中有以下屬性
url.2019=http://example.com/2019
url.2020=http://example.com/2020
而我有這個方法,
public String getUrl(String year) {
String url;
// here I want to read the property value based on the value of year
// if year is "2019", I want to get the value of ${url.2019}
// if year is "2020", I want to get the value of ${url.2020}
// something like #{url.#{year}} ??
return url;
}
實現這一目標的最佳方法是什么?
謝謝你。
可能有多種方法可以實現這一目標
如果您的房產不受 spring 管理
https://www.baeldung.com/inject-properties-value-non-spring-class
如果由 spring 管理
1.)您可以在 application.properies 中定義一個 map,可以在您的代碼中注入 map 讀取您想要的任何屬性
2)您可以按需注入環境變量和讀取屬性
@Autowired
private Environment environment;
public String getUrl(String year) {
String url = "url." + year ;
String value =environment.getProperty(url);
return url;
}
應用程序屬性:
url.2019=https://
url.2020=https://
代碼,對於 Map 字段,僅使用@ConfigurationProperties
是強制性的,否則,您將無法獲得值。
@Configuration
@PropertySource("put here property file path")
@ConfigurationProperties()
public class ConfigProperties {
@Value($("url"))
Map<String,String> urlMap;
public String getUrl(String year) {
String url = urlMap.get(year);
System.out.println(url);
}
}
我認為,一種選擇可能是使用.yml
文件
url:
2019: url1.com
2010: url2.com
2021: url3.com
然后您可以輕松閱讀以下屬性:
String year = // get year dynamically from somewhere
@Value("#{'url' + year}")
private String urlOfYear;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.