Nacos作为配置中心使用@RefreshScope注解在Controller层无效。

修改了Nacos配置中心的配置,在controller取值,刷新为null。

看了那么多说的解决办法,没一个靠谱的!!

最后研究了一下@RefreshScope注解

解决办法:

bootstrap配置文件

在这里插入图片描述

- 第一种方法

  • 新建一个CloudConfig实体,同时加上@RefreshScope 、@Configuration

@Configuration
@RefreshScope
public class CloudConfig {

    @Value("${aaa}")
    private String aaa;

    public String getAaa() {
        return aaa;
    }
}

  • 在Controller层将CloudConfig注入

@RestController
public class TestController {
    private Logger logger = LoggerFactory.getLogger(TestController.class);
    @Autowired
    private CloudConfig  config;
    
    @GetMapping("test")
    private String test(){
        String aaa=config.getAaa();
        return aaa;   
    }
}


- 第二种方法

  • 直接在@RefreshScope注解后面,配置默认值

在这里插入图片描述

更多推荐