本文适用版本
本文依赖所用版本
springboot 2.6.14
spring-cloud-dependencie 2021.0.6
spring-cloud-alibaba-dependencies 2021.0.4.0
根据文档
新版的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
注解的类不能自动注入@FeignClient
的Service
配置细节
本地application.yaml
和配置中心coupen.yaml
中,具有同名属性,优先使用配置中心的配置
版权属于:本文为原创文章,版权归 猫先生 所有
本文链接:https://loli.rip/index.php/archives/611/
转载时须注明出处及本声明