假设我的 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 中定义一个映射,可以在你的代码中注入(inject)映射读取你想要的任何属性
2) 您可以注入(inject)环境变量并按需读取属性
@Autowired
private Environment environment;
public String getUrl(String year) {
String url = "url." + year ;
String value =environment.getProperty(url);
return url;
}
关于java - 如何在 Spring Boot 中根据局部变量的值读取外部属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58637191/