Nacos配置动态更新失效原因

2,243 阅读1分钟

一、通常获取配置文件的方式包含两种

-   @Value
-   @ConfigurationProperties(Prefix)

1、nacos配置:

xx:
  tool:
    url: 'https://aliyun.com/aifile/elephant-v2.1.0.1.msi'

2、直接使用@Value 获取最新的工具下载地址

@Value(value = "${xx.tool.url:}")
private String url;
​
@GetMapping("tool_value")
public String getValueToolUrl() {
    return url;
}

发现获取不到最新

image-20211222142736539

要在bean上加@RefreshScope,获取到最新

image-20211222142842323

3、使用@ConfigurationProperties,添加配置获取类

@Data
@Component
@ConfigurationProperties(prefix = "xx.tool")
public class ToolProperties {
​
    private String url;
​
}
​

接口代码:

    @Resource
    private ToolProperties toolProperties;
​
    @GetMapping("tool_properties")
    public String getPropertiesToolUrl() {
        return toolProperties.getUrl();
    }

不需要@RefreshScope也能获取到更新

image-20211222143313621

总结:

如果是在运行时要动态更新的话,配合nacos使用时,配置更新时会自动调用nacos的NacosContextRefresher,此时

  • 第一种方式要在bean上加@RefreshScope
  • 第二种方式是自动支持的。