1.在服务中引入nacos作为配置中心的依赖
<!-- nacos作为配置中心来做配置管理 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
2.在服务的resource目录下创建一个bootstrap.properties配置文件,需要配置以下两项,第一项是服务的名字,根据实际服务配置
spring.application.name=xxxxxxxx
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
3.需要在配置中心中添加一个数据集(Data Id),默认规则是:应用名.properties
4. 动态获取配置,需要使用两个注解
@RefreshScope:动态获取并刷新配置
@Value("${配置项的名}"):获取到配置
5.在controller中创建一个测试,该测试的类上添加@RefreshScope注解动态获取配置
@Value("${coupon.user.name}")
private String name;
@Value("${coupon.user.age}")
private int age;
@RequestMapping("/test")
public R test(){
return R.ok().put("name",name).put("age",age);
}