如何在Spring Boot中读取基于本地变量值的外部属性



假设我的应用程序中有以下属性。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;
}

实现这一目标的最佳方式是什么?

谢谢。

有多种方法可以实现此

如果您的房产未由春季管理

https://www.baeldung.com/inject-properties-value-non-spring-class

如果由spring管理

1.(你可以在application.properies中定义映射,可以在你的代码中注入映射,读取你想要的任何属性

2( 您可以根据需要注入环境变量并读取属性

@Autowired 
private Environment environment;
public String getUrl(String year) {
String url = "url." + year ;
String value =environment.getProperty(url);
return url;
}

application.properties:

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);
}
}

最新更新