问题
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:
- add pom dependency:
spring-cloud-starter-consul-config
- enable consul config:
spring.cloud.consul.config.enabled=true
- 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
来源:https://stackoverflow.com/questions/54615291/read-values-from-consul-while-bootstrap-spring-boot