Creating a Spring cloud config server

Overview of Spring Cloud Config

Spring Cloud Config can be used to create a server side application to externalize configurations, but also for client side application for consuming configurations.

In this article we will focus on the server side part of Spring Cloud Config. We will create a simple project that will expose configuration files from our local disk.

Generating the project

We use Spring Initializr to generate a basic project with our required dependencies. For this project we use Java 8, Maven, Spring Boot and for dependencies, we just need Config Server.

Our Spring Initializr screen looks like this

Spring Initializr screen for generating a Spring Cloud Config server project
Spring Initializr

Configuring the application

To make your Spring Boot application into a config server all you have to do is just add the @EnableConfigServer annotation on the same class that is annotated with @SpringBootApplication.

This is how our main application class will look like:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}

As any other Spring Boot app, it will start on port 8080. For this project we use port 9999. To do that, we change the server.port property.

Spring needs to know where the configuration files are stored and how to load them. We can do this by configuring two properties, spring.profiles.active and spring.cloud.config.server.native.searchLocations.
Our final application configuration file will look like this:

server.port=9999
spring.profiles.active=native
spring.cloud.config.server.native.searchLocations=${HOME}/repo

The native profile will tell Spring to use the local classpath / or file system.
spring.cloud.config.server.native.searchLocations property will specify the location where configuration files are stored.
In our case it will look in the home directory of the current user in a folder called repo.

Starting the server

Go in the directory where your project is located and run the mvnw script

cd spring-cloud-config-server
./mvnw spring-boot:run

Conclusion

As you saw this is just a simple project that will read configuration files from your local machine. You can use other environments as well (Git, AWS, Redis etc). Head over to the Spring Cloud Config documentation for a more comprehensive guide on how to configure and use them.

The source code for this project can be found here.

References