How to wire up and use externally configurable variables in Spring Boot + Java
Spring Boot is awesome for many reasons, and one of them is the ease of setting up external configuration so that you can run the same application code in different environments or update variables at any time without going in and having to change the code itself.
This article will go over how to achieve this in your Java application with Spring Boot using the annotations
Config class declaration
First, you’ll have to create a Java class that will be a Spring Boot bean by way of the
In it, the variables will be the ones that you wish to be externally configurable. If these are
String values— like usernames or e-mail addresses, for example — then declare them as such; if these are
int values— like port numbers or thread counts, for instance — then declare those accordingly.
In this example, we have an
EmailConfig class that is used to configurable variables for sending e-mails in our code. We are allowing for the flexibility to:
- turn the functionality on and off with the
- edit the sender e-mail with the
- edit the list of recipient e-mails with the
- edit the subject of the e-mail with the
We can define default values for these in our
application.yml) file as follows:
What is important here is that these all have the prefix
@ConfigurationProperties annotation which is specifically looking for this prefix.
Spring Boot will work its own magic and then match up the variables according to their names; be careful with the capitalization, because Spring Boot will try to match according to its relaxed binding rules.
In this example, I adhered to the camelCase convention, but you also could have defined
email.sender-email (using a hyphen) or
email.sender_email (using an underscore) and would have been fine as well thanks to Spring Boot.
Using the configs in code
Now that we have the bean
EmailConfig, we can use it in our Java application as follows:
Note that for simplicity’s sake, this is just an example where we are testing that the configuration set-up works by printing out the values into our console. In your real application, you would then be able to use those variables like you would hard-coded ones in order to carry out the logic of sending e-mails.
External configuration is absolutely crucial when it comes to reducing manual steps and unnecessary code changes and deployments, and it’s a key feature of Spring Boot that needs to be taken advantage of.
I hope that you have a better idea of how to do it with this specific approach, and for further reading I would strongly recommend reading the Spring Boot documentation on this subject.