本文适用版本

本文依赖所用版本

springboot 2.6.14
spring-cloud-dependencie 2021.0.6
spring-cloud-alibaba-dependencies 2021.0.4.0

根据文档

Srping Cloud Alibaba Github

Nacos Config Example

新版的nacos配置中心不需要bootstrap.yaml,直接在application.yaml中配置

spring:
  cloud:
    nacos:
      serverAddr: 127.0.0.1:8848
  config:
    import:
      - nacos:coupen.yaml?refresh=true

配置热更新

新建一个Nacos配置coupen.yaml


coupen:
    user:
        age: 14
        name: coupen-zhangsan1112333444

新建一个实体类,把自己自定义的配置通过@Value注解注入到属性

@RefreshScope
@Component
@Data
public class MyConfig {
    @Value("${coupen.user.name}")
    private String name;
    @Value("${coupen.user.age}")
    private Integer age;
}

在Service中通过自动注入,调用get方法获取值

@Autowired
private MyConfig myConfig;

@GetMapping("/member/list")
private R membercoupns() {
    CouponEntity couponEntity = new CouponEntity();
    couponEntity.setCouponName("满100-10");
    System.out.println(myConfig.getName());
    System.out.println(myConfig.getAge());
    return R.ok().put("coupens", Arrays.asList(couponEntity));

}

需要注意的是新版的SpringCloud@RefreshScope写在Controller上,通过@Value注入的属性取值为Null,且@RefreshScope注解的类不能自动注入@FeignClientService

配置细节

本地application.yaml和配置中心coupen.yaml中,具有同名属性,优先使用配置中心的配置

Last modification:March 18th, 2023 at 09:07 pm
如果觉得我的文章对你有用,请随意赞赏