java 在 spring boot 中通过动态键读取属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39240963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 04:11:57  来源:igfitidea点击:

Read properties by dynamic keys in spring boot

javaspringspring-boot

提问by rishi

I wanted to know if there is any way in Spring Boot to read property values from properties file by using Dynamic Keys. I know properties can be put in application.propertiesand can be read using @Value("propertyKey")But my keys are going to be dynamic.

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

I know about @PropertySourceto read property values and I can construct my keys dynamically. So is there any way that is provided by Spring Boot?

我知道@PropertySource要读取属性值,并且可以动态构造我的键。那么有没有Spring Boot提供的方法呢?

回答by freakman

you can use:

您可以使用:

@Autowired
private Environment env;

and then load property from code:

然后从代码加载属性:

env.getProperty("your.property")

回答by Neeraj Gahlawat

  1. Register a Properties File via Java Annotations.

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

    }

  2. Dynamically select the right file at runtime.

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

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

    @Configuration @PropertySource("classpath:test.properties") 公共类 PropertiesJavaConfig {

    }

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

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