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

Java 在spring boot中通过动态键读取属性,java,spring,spring-boot,Java,Spring,Spring Boot,我想知道在SpringBoot中是否有任何方法可以通过使用动态键从属性文件中读取属性值。我知道属性可以放在应用程序中。属性可以使用@Value(“propertyKey”)读取,但我的密钥将是动态的 我知道如何使用@PropertySource读取属性值,并且可以动态构造密钥。那么Spring Boot提供了什么方法呢?您可以使用: @Autowired private Environment env; 然后从代码中加载属性: env.getProperty("your.property")

我想知道在SpringBoot中是否有任何方法可以通过使用动态键从属性文件中读取属性值。我知道属性可以放在
应用程序中。属性可以使用
@Value(“propertyKey”)
读取,但我的密钥将是动态的

我知道如何使用
@PropertySource
读取属性值,并且可以动态构造密钥。那么Spring Boot提供了什么方法呢?

您可以使用:

@Autowired
private Environment env;
然后从代码中加载属性:

env.getProperty("your.property")

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

@Configuration
@PropertySource("classpath:test.properties")
public class PropertiesJavaConfig {
    
}
@PropertySource({ 
  "classpath:persistence-${envTarget:DB}.properties"
})
2-在运行时动态选择正确的文件。

@Configuration
@PropertySource("classpath:test.properties")
public class PropertiesJavaConfig {
    
}
@PropertySource({ 
  "classpath:persistence-${envTarget:DB}.properties"
})

如果您正在从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);
    }    
 }