Spring boot Get properties from consul server

The Strong Programmer picture The Strong Programmer · Mar 2, 2017 · Viewed 7.1k times · Source

I have a spring boot application and I would like to get properties that I have on a consul agent.

@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages={"com.commons"})
public class MainAppProxy   implements CommandLineRunner {      
    @Value("${proxy.endpoint}")
    private String endpointAddress;

My application.properties is under src/main/resources

spring.application.name=SOAPProxy
spring.cloud.consul.host=http://10.0.1.241
spring.cloud.consul.port=8500
spring.cloud.config.discovery.enabled=false

in pom.xml I have the following config (short version)

            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.SR5</version>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>

The properties are stored on consul in this format: Business/SOAPProxy/proxy.endpoint

When the application boots, it seems that it finds consul but it cannot get the values as it could before trying consul @Value("${proxy.endpoint}") How can I get the properties on consul?

Answer

wthamira picture wthamira · Mar 9, 2017

You can use three way to load configuration from consul

  1. key/value
  2. yaml
  3. file

I used in yaml to load configuration.

This is my bootstrap.yml file (you can use .property file also)

spring:
  application:
    name: SOAPProxy

---

spring:
  profiles: default
  cloud:
    consul:
      config:
        data-key: data
        prefix: config
        format: yaml
      host: localhost
      port: 8500
      discovery:
        prefer-ip-address: true  

my boot app Annotate like below

@EnableDiscoveryClient
@EnableAutoConfiguration
@SpringBootApplication
public class SpringBootConsulApplication {

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

maven dependancy add like this

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>

this is configuration of consul agent key/value

enter image description here

now in startup all configuration load to the application