前文《Spring Cloud Config里使用Git作为后端存储来开发ConfigServer》已经介绍了如何配置Config Server配置中心,本文将介绍如何在Spring Cloud微服务获取配置中心Config Server配置信息。
一、创建一个新的微服务,整合Config Client
1.pom文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
<artifactId>deviceservice-config-client</artifactId> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> |
2.配置文件application.yml
1 2 |
server: port: 8081 |
3.配置文件bootstrap.yml
1 2 3 4 5 6 7 8 9 10 11 |
spring: application: # 对应config server所获取的配置文件的{application} name: deviceservice-foo cloud: config: uri: http://localhost:8080/ # profile对应config server所获取的配置文件中的{profile} profile: dev # 指定Git仓库的分支,对应config server所获取的配置文件的{label} label: master |
- spring.application.name:对应Config Server 所获取的配置文件中的{application}
- spring.cloud.config.uri:指定Config Server 的地址,默认是http://localhost:8888
- spring.cloud.config.profile:profile对应Config Server所获取的配置文件中的{profile}
- spring.cloud.config.label:指定Git仓库的分支,对应Config Server所获取配置文件的{label}
需要注意的是,以上属性必须配置在bootstrap.yml文件中,而不是application.yml。具体原因参看这篇文章《SpringBoot中配置文件bootstrap和application的区别比较》。
4.ConfigClientController类
1 2 3 4 5 6 7 8 9 10 |
@RestController public class ConfigClientController { @Value("${profile}") private String profile; @GetMapping("/profile") public String hello() { return this.profile; } } |
5.启动类
1 2 3 4 5 6 |
@SpringBootApplication public class ClientApplication { public static void main(String[] args) throws Exception { SpringApplication.run(ClientApplication.class, args); } } |
在Controller中,通过注解@Value(“${profile}”),绑定Git仓库配置文件中的profile属性。
二、测试
1.启动deviceservice-config-server(前文所编写)
2.启动deviceservice-config-client
3.访问http://localhost:8081/profile,可获得如下结果

说明Config Client能够正常通过Config Server获得Git仓库中对应环境的配置。
+1
博主您好,我按照博文的描述,新建的config server可以访问仓库中的文件内容,但是通过config client就获取不到了,运行服务提示Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'title' in value "${title}",看了很多文章,也没找到方法怎么解决,请问能帮忙看一下吗?