DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Externalize Microservice Configuration With Spring Cloud Config
  • How to Setup the Spring Cloud Config Server With Git
  • A New Era Of Spring Cloud
  • Preserving Context Across Threads

Trending

  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Jakarta EE 11 and the Road Ahead With Jakarta EE 12
  • Are Traditional Data Warehouses Being Devoured by Agentic AI?
  • Making AI Faster: A Deep Dive Across Users, Developers, and Businesses
  1. DZone
  2. Software Design and Architecture
  3. Cloud Architecture
  4. Microservices: Access Properties From Spring Cloud Config Server

Microservices: Access Properties From Spring Cloud Config Server

Learn how to write a microservice that can be used to access centralized properties files on a Spring Cloud config server.

By 
Shaamik Mitraa user avatar
Shaamik Mitraa
·
Jul. 07, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
47.8K Views

Join the DZone community and get the full member experience.

Join For Free

In my previous microservice series, I discussed how to configure a config server step by step. Here I will show you how to access those centralized properties files from the Config server.

To start with, we have to write a small microservice which has a config property in the Config server, and use that property in this microservice.

Step 1: Create a project template from https://start.spring.io/. While creating the template, choose the following modules:

  1. Config Client
  2. Actuator
  3. Spring-Web
  4. Jersey 

Then hit the Generate Project button to download the template.

Image title

Step 2: Import the Template project as Maven project in Eclipse.
Step 3: Now change the application.properties file to bootstrap.properties and place the following properties there:

spring.application.name=EmployeeSearchService
server.port=8080
spring.cloud.config.uri=http://localhost:9090


Property Name

Value

Description

spring.application.name

EmployeeSearchService

A unique name(Service ID) for the service we will create a properties file in configserver based on this ServiceID


server.port

8080

It determines in which port this service will be running.

spring.cloud.config.uri

http://localhost:9090

It is the URL of config server please note that if config server has a ServiceID we can change it to http://{serviceID}:{port}  If there are multiple configServers behind a Load balancer we can give the public ip of load balancer

http://{loadbanacer-public-ip}:port

Step 4: The pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>EmployeeSearchService</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>EmployeeSearchService</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Dalston.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jersey</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <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>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

Step 5: Now create EmployeeSearchService.properties file under {user.home}/CentralRepo.

It is the filesystem from where configServer reads the properties file.

Please note that we provide the unique serviceID value as  EmployeeSearchService in spring.application.name property so we will create a properties file name EmployeeSearchService.properties ({serviceID}-{profile{.properties) considering the profile value as default.

cd CentralRepo
touch EmployeeSearchService.properties
vi EmployeeSearchService.properties
Hit insert
Write name=Shamik Mitra
Hit esc and wq!

Step 6: Now create a package called com.example.EmployeeSearchService.controller and create a RestController called GreetController .

/**
*
*/
package com.example.EmployeeSearchService.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
* @author Shamik Mitra
*
*/
@RefreshScope
@RestController
public class GreetController {

    @Value("${name}")
    private String personName;

    @RequestMapping("/greeting")
    public String greet(){

        return "hello " + personName;
    }

}


Please notice the annotation @Value("${name}"). This name property value actually fetches from the EmployeeSearchService.properties which we had created earlier. EmployeeSerachService find the properties file from the central server and fetch that name property and cached in local memory so the Central server has to be up before the EmployeeSearchService. Once EmployeeSearchService is up and running it can consult local cache so in the meantime if ConfigServer goes down that will not create such problem.

I use the @RefreshScope annotation so that if any property value changes in configServer that can be propagated to EmployeeSearchService without restarting the application for that we need to hit the
http://localhost:8080/refresh endpoint which is the Actuator endpoint; by doing this latest property value will be reflected in EmployeeSearchService we will test that in a later section.

Step 7: Now run the ConfigServer first, then EmployeeSearchServiceApplication as a Java Project.

package com.example.EmployeeSearchService;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class EmployeeSearchServiceApplication {

public static void main(String[] args) {
SpringApplication.run(EmployeeSearchServiceApplication.class, args);
}
}

Once both are up and running, please hit the following URL in the browser: http://localhost:8080/greeting.

Output : Hello Shamik Mitra.

Now try to change the value of the name property:

cd CentralRepo
touch EmployeeSearchService.properties
vi EmployeeSearchService.properties
Hit insert
Edit name=Samir Mitra
Hit esc and wq!

Now hit the URL again (http://localhost:8080/greeting). We see it shows the old value.

Output : Hello Shamik Mitra.

Now we hit the actuator endpoint refresh (http://localhost:8080/refresh) and hit http://localhost:8080/greeting.

Output : Hello Samir Mitra.

About URL: To check the properties values for a microservice in the Central Config server, we have to call the REST endpoint of the Config server.We can build the config server endpoint URL in this manner: http://{Config server URL}:{Port}/{ServiceID}/{Profile} So if we want to see all the properties value in config server for the MicroServiceEmployeeSearchService, the URL should be http://localhost:9090/EmployeeSearchService/default.

Property (programming) microservice Spring Cloud

Opinions expressed by DZone contributors are their own.

Related

  • Externalize Microservice Configuration With Spring Cloud Config
  • How to Setup the Spring Cloud Config Server With Git
  • A New Era Of Spring Cloud
  • Preserving Context Across Threads

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • [email protected]

Let's be friends: