Microservices – Getting Properties from Config Server

In the previous post, we talked about standing up a Spring Cloud Config server. In this post, we will discuss how client applications can get different properties for different environments like development, test, production etc from the Config server.

If you rather watch the video on what’s in this post, see below, otherwise continue reading.

First, let’s make sure, your Config server is running as indicated in the previous post.

Next, create a client application to test the Config server.  Go to the Spring Initializr site https://start.spring.io/ and in the dependencies search box add web, config client dependencies (notice that for the Config server in the previous post, we added Config server as a dependency) and click on Generate Project to download an empty Spring boot project.

Create a file named bootstrap.properties or bootstrap.yaml in the resources folder and add the following properties.

The first property sets the name of the application. Note, this should exactly match the name of the properties file you created in the previous post (remember you created a property file called clientapp.properties). This is how the Spring Config server knows, what properties to serve to this application.

The second property indicates where the Config server is running. To see what properties are available to this application from the Config server go to http://localhost:8888/clientapp/default.

To your main class add a RestContoller

Start the clientapp application and go to http://localhost:8080/message in your browser, you should see I am a property from Config server for Development Environment.

How to specify environment specific properties

Go to the Git repo you created in the previous post and create a new branch for the production environment.

Now, edit clientapp.properties as shown below and commit the change.

In your clientapp project add an additional property to bootstrap.properties

This specifies which Git branch you want Config server to serve your properties. If you do not specify the label, Config server uses master branch by default.

Here is the whole bootstrap.properties.

Restart the clientapp application and to go to http://localhost:8080/message in your browser, you should see I am a property from Config server for Production Environment.

Download the sample code from my microservices Github repo.

Final Thoughts

Instead of using different branches to store properties for different environments, you can also use different repos.

In most cases, you can also use application.properties instead of bootstrap.properties. but note that bootstrap gets higher precedence. I think it is better to keep external properties in bootstrap and the rest in applcation.properties for a clean separation.