【问题标题】:Read properties by dynamic keys in spring boot在spring boot中通过动态键读取属性
【发布时间】:2017-01-07 12:48:39
【问题描述】:
我想知道 Spring Boot 中是否有任何方法可以使用 Dynamic Keys 从属性文件中读取属性值。我知道属性可以放在application.properties 中并且可以使用@Value("propertyKey") 读取但我的键将是动态的。
我知道@PropertySource 可以读取属性值,并且我可以动态构造我的键。那么Spring Boot有没有提供什么方式呢?
【问题讨论】:
标签:
java
spring
spring-boot
【解决方案1】:
如果您从 application.properties 中读取,您只需定义由freakman (org.springframework.core.env.Environment) 指定的环境spring autowired 变量。但是,如果您使用的是特定于某些属性的新属性文件,则可以使用以下代码:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@Configuration
@PropertySource("classpath:filename.properties")
public class CustomConfig {
@Autowired
Environment env;
public String getProperty(String keyName) {
return env.getProperty(keyName);
}
}
【解决方案2】:
1- 通过 Java 注释注册属性文件。
@Configuration
@PropertySource("classpath:test.properties")
public class PropertiesJavaConfig {
}
2- 在运行时动态选择正确的文件。
@PropertySource({
"classpath:persistence-${envTarget:DB}.properties"
})
【解决方案3】:
你可以使用:
@Autowired
private Environment env;
然后从代码中加载属性:
env.getProperty("your.property")