首页 文章

在Spring Cloud 配置客户端之间共享配置

提问于
浏览
5

我正在尝试使用具有基于文件的存储库的Spring Cloud配置服务器在Spring Cloud客户端之间共享配置:

@Configuration
@EnableAutoConfiguration
@EnableConfigServer
public class ConfigServerApplication {

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

// application.yml
server:
  port: 8888

spring:
  profiles:
    active: native

test:
  foo: world

我的一个Spring Cloud客户端使用配置服务器中定义的 test.foo 配置,配置如下:

@SpringBootApplication
@RestController
public class HelloWorldServiceApplication {

    @Value("${test.foo}")
    private String foo;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    @ResponseBody
    public String helloWorld() {
        return "Hello " + this.foo;
    }

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

// boostrap.yml
spring:
  cloud:
      config:
        uri: ${SPRING_CONFIG_URI:http://localhost:8888}
      fail-fast: true

// application.yml
spring:
  application:
    name: hello-world-service

尽管有这样的配置,Spring Cloud Client中的 Environment 不包含 test.foo 条目(参见 java.lang.IllegalArgumentException: Could not resolve placeholder 'test.foo'

但是,如果我将属性放在 hello-world-service.yml 文件中,在我的配置服务器基于文件的存储库中,它的工作方式非常有效 .

使用spring-cloud-starter-config和spring-cloud-config-server对Spring Cloud Brixton.M5和Spring Boot 1.3.3.RELEASE进行Maven依赖

1 回答

  • 1

    Spring Cloud documentation

    使用“本机”配置文件(本地文件系统后端)时,建议您使用不属于服务器自身配置的显式搜索位置 . 否则,将删除默认搜索位置中的应用程序*资源,因为它们是服务器的一部分 .

    所以我应该将共享配置放在外部目录中,并在 config-serverapplication.yml 文件中添加路径 .

    // application.yml
    spring:
      profiles:
        active: native
      cloud:
        config:
          server:
            native:
              search-locations: file:/Users/herau/config-repo
    
    // /Users/herau/config-repo/application.yml
    test:
      foo: world
    

相关问题