In order for an Spring application to use Spring Cloud Config Server, we can build an Spring application that depends on spring-cloud-config-client
Before we begin, it’s recommended to have already completed Configure Spring Cloud Config Server. We’re going to take an existing cloud config server for this post.
In order to add Config client to project, add below dependencies.
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
The properties to configure the Config Client must necessarily be read in before the rest of the application’s configuration is read from the Config Server, during the bootstrap phase.
When a config client starts, it binds to the Config Server (through the spring.cloud.config.uri bootstrap configuration property) and initializes Spring Environment with remote property sources. Provide below properties in bootstrap.properties
spring.cloud.config.uri=${config.url:http://localhost:8001} spring.application.name=rest
@RestController public class MyRestController { @Autowired private ApplicationProperties properties; @GetMapping("/hello") public ResponseEntity<String> hello(){ return new ResponseEntity<String>("Hi !!!"+ properties.getGreeting(), HttpStatus.OK); } }
ApplicationProperties file holds all the properties of application and uses ConfigurationProperties.
@Bean @ConfigurationProperties(prefix = "rest") @RefreshScope public ApplicationProperties applicationProperties() { return new ApplicationProperties(); }
Let us suppose the active profile for application is dev.
Now when the application starts, it will try to connect to config server url and read a file with name rest-dev.yml
or <strong>rest-dev.properties</strong>
. (spring.application.name)-(spring.profiles.active)
Hit the url
http://localhost:8080/hello
Response :
Hello User!!
The value of property rest.greeting
is injected in the controller via config server.
In the next article we will configure Spring Cloud Bus. It helps in refreshing the configuration to reflect changes to the Config Server on-demand, without restarting the JVM.