I have a Spring Boot application that uses Spring profiles to create environment specific configurations, for example:
@Configuration @Profile("local") public class LocalConfiguration ... @Configuration @Profile("prod") public class ProdConfiguration ...
I have a @RestContoller that needs to access the values that the configurations load from application.properties
. How can I inject the current environment specific configuration bean inside the controller?
Example:
@Autowired private <config_based_on_env_here> config; @RestController public String getSomeString() { return config.getSomeString(); }
Advertisement
Answer
If you need to access values from the application.properties
or .yaml
configuration you could use a much simpler way for achieving this.
Firstly configure different configs:
application-local.properties
my.value=local-value
application-prod.properties
my.value=prod-value
Create a configuration for reading needed value:
@Configuration @ConfigurationProperties(prefix = "my") public class ConfigProperties { private String value; // standard getters and setters }
Finally, you could autowire this configuration at the controller:
@RestController class MyController { @Autowire private ConfigProperties config; @GetMapping("/hello") public void hello() { System.out.println("Config value: " + config.getValue()); } }
When you run your app with the needed profile – the appropriate config file will be loaded and accessed at the controller.
Also, you could have a look at @Value annotation
Additional resources: