How to access externalized configuration values programmatically in spring boot

Spring Boot come up with a very comprehensive configuration mechanism. This allows developers to change application behavior externally via configuration files, environment variables, configuration servers (in this case spring-cloud-config), etc. To see all possible ways to configure a spring boot application please take a look at respective part of official reference documentation.

In this article, we will discuss how to access this configuration values from our code.

In most of the cases, you can use @Value annotation to inject a specific configuration value into your code.

@Value("${property.key.name.from.application.properties}")
private String someConfiguration;

This construct is very simple and effective. But in a very rare case, you may not know the key name of the configuration property (in above example property.key.name.from.application.properties) and the key name may be a variable defined at runtime or provided by another class. In this case, you can use Environment class of Spring.

What you have to do is simply auto wire the Environment instance into your class and call getProperty() method.

@Component
public class YourImplementation {

    @Autowired
    private Environment environment;

    ...
    
    private String resolveConfigurationValue(String key) {
         return environment.getProperty(key);
    }
}

 

Leave a reply