問題描述:
nacos修改了配置,但是@Value沒有動態刷新
解決辦法:
在使用Nacos作為配置中心時,除了@NacosValue可以做到自動刷新外,nacos-spring-context:0.3.4版本是支持@Value獲取Nacos配置中心的值,並動態刷新的,該功能是Spri依靠ngValueAnnotationBeanPostProcessor類來實現:
@Override protected Tuple<String, NacosValueTarget> doWithAnnotation(String beanName, Object bean, Value annotation, int modifiers, Method method, Field field) { if (annotation != null) { if (Modifier.isStatic(modifiers)) { return Tuple.empty(); } if (bean.getClass().isAnnotationPresent(NacosRefresh.class)) { String placeholder = resolvePlaceholder(annotation.value()); if (placeholder == null) { return Tuple.empty(); } NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName, method, field); nacosValueTarget.setAnnotationType(getAnnotationType().getSimpleName()); logger.debug("@Value register auto refresh"); return Tuple.of(placeholder, nacosValueTarget); } } return Tuple.empty(); }
分析其源碼可以看到,如果bean上有注解@NacosRefresh,則會自動刷新。
在實際使用時,發現bean上的注解是@Configuration則不會自動刷新,而使用@Component則可以做到自動刷新。
這就和@Component與@Configuration的區別有關了,@Component注解的bean是原生bean,@Configuration是被cglib動態增加的bean。
另一種解決辦法:
將配置映射到實體對象,上面添加@RefreshScope 可以實現動態刷新 用@value注入的配置文件無法刷新。 @RefreshScope @ConfigurationProperties(prefix = "user") @Component @DaTa public class User { private String name; }
在含有@Value屬性的類上加注解@RefreshScope 把配置信息寫在nacos配置中心就好啦,之后改變值就會自動刷新,不需要重啟項目
個人經驗,也試過了,可以自動刷新,希望對你有所幫助!