Read values from consul while bootstrap spring boo

2019-08-16 17:24发布

问题:

I have question is there any way to retrieve certain values and inject them to bootstrap.yml while application is coming up.

I have configuration file like this:

spring:
  application:
    name: myApp

  cloud:
    consul:
      enabled: true
      host: localhost
      port: 8500
      config:
        enabled: true

  datasource:
    url: jdbc:oracle:thin:@localhost:1111:XXXX
    username: ${nameOfVariable1}
    password: ${nameOfVariable1}
    driver-class-name: oracle.jdbc.OracleDriver

For example, I need to configure embedded tomcat port, or DB credentials, I don't want to put it hardcoded in .yml properties file, instead I want to put some variable name in .yml so Spring will go and bring value from Consul. Is it possible?

回答1:

You can use Spring Cloud Consul Config project that helps to load configuration into the Spring Environment during the special "bootstrap" phase.

3 steps:

  1. add pom dependency: spring-cloud-starter-consul-config
  2. enable consul config: spring.cloud.consul.config.enabled=true
  3. add some config in consul kv in specific folder, such as key: config/testConsulApp/server.port, value:8081

and then start the sample web app, it will listen 8081.

more detail at spring cloud consul doc.

and demo code here