By default, Spring Boot will try to connect to the Consul agent at localhost:8500. To use other settings, we need to update the application.yml file:

spring:
cloud:
consul:
host: localhost
port: 8500

Then, if we visit the Consul agent’s site in the browser at http://localhost:8500, we’ll see that our application was properly registered in Consul with the identifier from “${spring.application.name}:${profiles separated by comma}:${server.port}”.

To customize this identifier, we need to update the property spring.cloud.discovery.instanceId with another expression:

Spring Cloud Consul Config will look for the properties in Consul at “/config/myApp”. So if we have a property called “my.prop”, we would need to create this property in the Consul agent site.

We can create the property by going to the “KEY/VALUE” section, then entering “/config/myApp/my/prop” in the “Create Key” form and “Hello World” as value. Finally, click the “Create” button.

Bear in mind that if we are using Spring profiles, we need to append the profiles next to the Spring application name. For example, if we are using the dev profile, the final path in Consul will be “/config/myApp,dev”.

Now, let’s see what our controller with the injected properties looks like:

If we run the application, the field value and properties have the same “Hello World” value from Consul.

5.1. Updating the Configuration

What about updating the configuration without restarting the Spring Boot application?

If we go back to the Consul agent site and we update the property “/config/myApp/my/prop” with another value like “New Hello World”, then the field value will not change and the field properties will have been updated to “New Hello World” as expected.

This is because the field properties is a MyProperties class has the @RefreshScope annotation. All beans annotated with the @RefreshScope annotation will be refreshed after configuration changes.

In real life, we should not have the properties directly in Consul, but we should store them persistently somewhere. We can do this using a Config Server.

6. Conclusion

In this article, we’ve seen how to set up our Spring Boot applications to work with Consul for Service Discovery purposes, customize the health checking rules and share a distributed configuration.

We’ve also introduced a number of approaches for the clients to invoke these registered services.