Skip to content
Advertisement

How to access configuration beans in Spring controllers

I have a Spring Boot application that uses Spring profiles to create environment specific configurations, for example:

JavaScript

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:

JavaScript

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

JavaScript

application-prod.properties

JavaScript

Create a configuration for reading needed value:

JavaScript

Finally, you could autowire this configuration at the controller:

JavaScript

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:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement