使用Spring的@Value从Nacos配置中心获取值并自动刷新

时间:2025-02-13 07:20:11

 在使用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 ((modifiers)) {
				return ();
			}

			if (().isAnnotationPresent()) {
				String placeholder = resolvePlaceholder(());

				if (placeholder == null) {
					return ();
				}

				NacosValueTarget nacosValueTarget = new NacosValueTarget(bean, beanName,
						method, field);
				(getAnnotationType().getSimpleName());
				("@Value register auto refresh");
				return (placeholder, nacosValueTarget);
			}
		}
		return ();
	}

 分析其源码可以看到,如果bean上有注解@NacosRefresh,则会自动刷新。

在实际使用时,发现bean上的注解是@Configuration则不会自动刷新,而使用@Component则可以做到自动刷新。代码如下:

@NacosRefresh
//@Component
@Configuration
public class BeanTest {
    
    @Value("${}")
    private String testValue;
    
    
    @NacosValue(value="${autofresh.test2}",autoRefreshed = true)
    private String testValue2;

    /**
     * @return the testValue2
     */
    public String getTestValue2() {
        return testValue2;
    }

    /**
     * @param testValue2 the testValue2 to set
     */
    public void setTestValue2(String testValue2) {
        this.testValue2 = testValue2;
    }

    /**
     * @return the testValue
     */
    public String getTestValue() {
        return testValue;
    }

    /**
     * @param testValue the testValue to set
     */
    public void setTestValue(String testValue) {
         = testValue;
    }
    
    
    

}

测试类:

@Test
     public void testValueRefreshinNacos() throws InterruptedException {
        (());
        (beanTest.getTestValue2()); 
        ("------修改前");
        
        (1000*60);
        
        (());
        (beanTest.getTestValue2()); 

        ("------修改后");
     }

 这就和@Component与@Configuration的区别有关了,@Component注解的bean是原生bean,@Configuration是被cglib动态增加的bean。