在 Spring Boot 中按动态键读取属性

2022-09-03 04:09:12

我想知道在Spring Boot中是否有任何方法可以使用动态键从属性文件中读取属性值。我知道属性可以放入,可以使用读取,但我的键将是动态的。application.properties@Value("propertyKey")

我知道要读取属性值,我可以动态构造我的键。那么Spring Boot提供了什么方法吗?@PropertySource


答案 1

您可以使用:

@Autowired
private Environment env;

,然后从代码中加载属性:

env.getProperty("your.property")

答案 2

1- 通过 Java 注释注册属性文件。

@Configuration
@PropertySource("classpath:test.properties")
public class PropertiesJavaConfig {
    
}

2-在运行时动态选择正确的文件。

@PropertySource({ 
  "classpath:persistence-${envTarget:DB}.properties"
})

推荐