使用 Spring Cloud Consul 无法读取远程 属性

Fail to read remote property using Spring Cloud Consul

我们计划将大量 .properties 文件的内容移至 Consul 我已经实现了一个具有以下定义的演示

@EnableAutoConfiguration
@SpringBootApplication
@EnableDiscoveryClient
@RestController
@EnableConfigurationProperties
public class Application {

    @Autowired
    private Environment env;

    @RequestMapping("/")
    public String home() {
        return env.getProperty("dc1/kv/property1/");
    } 
}

默认使用 consul 服务器 运行

目前env.getProperty("dc1/kv/property1/");returns没有

我的 pom 看起来像这样

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

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
</properties>

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

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Brixton.SR6</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-consul-dependencies</artifactId>
            <version>1.0.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-consul-all</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

任何人都可以开灯吗

您不像 consul 那样引用属性,而是像 spring 属性那样引用它们。默认情况下,spring-cloud-consul 在 /config 上下文中查找。您是否需要将 property1 放入 /config/property1 并通过 env.getProperty("property1") 引用它。对于 /config/foo/property,您将在 spring 的环境中引用 foo.property