在启动Spring Boot时从领事读取值

时间:2019-02-10 10:02:25

标签: spring spring-boot consul spring-cloud-consul

我有一个问题,有什么方法可以检索某些值,并在应用程序启动时将它们注入bootstrap.yml。

我有这样的配置文件:

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

例如,我需要配置嵌入式tomcat端口或数据库凭据,我不想将其硬编码在.yml属性文件中,而是想在.yml中放置一些变量名,这样Spring就会开始使用领事的价值。有可能吗?

1 个答案:

答案 0 :(得分:1)

您可以使用Spring Cloud Consul Config项目,该项目有助于在特殊的“引导”阶段将配置加载到Spring环境中。

3个步骤:

  1. 添加pom依赖项:spring-cloud-starter-consul-config
  2. 启用领事配置:spring.cloud.consul.config.enabled=true
  3. 在领事kv的特定文件夹中添加一些配置,例如密钥:config/testConsulApp/server.port,值:8081

然后启动示例Web应用程序,它将监听8081。

spring cloud consul doc上有更多详细信息。

demo code here