Skip to content
Advertisement

Spring Boot – having all autowired config variables in one class

I am working on a microservice in Spring Boot, and I have a common configuration class where I store all the config variabes that I got from application.properties file. It looks something like this:

Config.java

JavaScript

Then whenever I need these variables in other classes, I autowire Config.java class, and simply use it like this:

JavaScript

Would having a common configuration class that stores all the autowired variables and use these when needed in other classes a good practice in spring boot? If not, what would be the best way to go about this? Any help would be greatly appreicated. Thank you!

Advertisement

Answer

The better way is to do something ging like this

JavaScript

In your application.properties you can now type

JavaScript

You can the Autowerire MyProperties where ever you need them

Edit It’s also good to add the following dependency to maven, it generates a helper file so that your idea can recognise the defined properties

JavaScript

Small addition to replay on the question in the comments You can leave the prefix empty and just annotate you class with @ConfigurationProperties if you don’t want to have a general key Subkeys can be easily handled with subclasses I will post an example of one of my projects here

JavaScript

example application.yml

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