Spring的@Value如何从Nacos配置中心获取值并自动刷新
作者:chuixue24 时间:2022-03-11 02:17:03
@Value从Nacos配置中心获取值并自动刷新
在使用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则可以做到自动刷新。
代码如下:
@NacosRefresh
//@Component
@Configuration
public class BeanTest {
@Value("${autofresh.test}")
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) {
this.testValue = testValue;
}
}
测试类:
@Test
public void testValueRefreshinNacos() throws InterruptedException {
System.out.println(beanTest.getTestValue());
System.out.println(beanTest.getTestValue2());
System.out.println("------修改前");
Thread.sleep(1000*60);
System.out.println(beanTest.getTestValue());
System.out.println(beanTest.getTestValue2());
System.out.println("------修改后");
}
这就和@Component与@Configuration的区别有关了,@Component注解的bean是原生bean,@Configuration是被cglib动态增加的bean。
Nacos属性值自动刷新
1.@NacosValue获取最新值
引入jar包:
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.7</version>
</dependency>
编写配置类:
@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848"))
@NacosPropertySource(dataId = "example", group="test",autoRefreshed = true)
public class NacosConfiguration { }
编写测试类:
@Controller
public class ConfigController {
@NacosValue(value = "${test.data}", autoRefreshed = true)
private boolean data;
@RequestMapping(value = "/test", method = GET)
@ResponseBody
public boolean get() { return data; }
}
2.@Value获取最新值
引入jar包:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
引入配置:
spring:
application:
name: example
cloud:
nacos:
config:
extension-configs[0]:
dataId: test.yml
group: test
refresh: true
server-addr: 127.0.0.1:8848
namespace: c845e96f-4423-4618-8c26-5e4d510f566a
enabled: true
refresh-enabled: true
编写测试类:
@RestController
@RefreshScope
public class TestController {
@NacosValue(value = "${test.data}", autoRefreshed = true)
private String data;
@Value(value = "${test.data}")
private String datas;
@GetMapping("test")
public String test() {
return "data :" + data + ",datas="+datas;
}
}
备注:
方式一@NacosValue获取最新值nacos配置信息需要写在配置类上
方式二@NacosValue获取不到值(如果需要使用该注解需要引入方式一的jar,但是不重启服务获取不到最新值),@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true
来源:https://blog.csdn.net/chuixue24/article/details/107386045
标签:Spring,@Value,Nacos配置,自动刷新
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Idea Jrebel 报错:Cannot reactivate,offline seat in use
2022-01-11 05:08:22
![](https://img.aspxhome.com/file/2023/6/60576_0s.png)
Java单例模式、饥饿模式代码实例
2022-04-15 22:22:06
Java 二分查找算法的实现
2022-07-23 11:10:13
详解Java中的时区类TimeZone的用法
2023-11-29 02:03:09
Mybatis如何配置连接池
2021-10-22 03:06:47
SpringBoot配置拦 截器实现过程详解
2023-11-24 17:14:58
通过Java实现bash命令过程解析
2023-01-07 17:38:25
Maven分模块开发执行指令失败的问题
2021-07-10 19:00:15
![](https://img.aspxhome.com/file/2023/0/72560_0s.jpg)
Java中异常处理之try和catch代码块的使用
2021-11-21 13:30:23
Java实现求二叉树的深度和宽度
2022-01-11 18:38:41
C#实现IP摄像头的方法
2023-12-09 03:42:51
C#线程入门教程之单线程介绍
2022-03-15 20:37:28
![](https://img.aspxhome.com/file/2023/9/69819_0s.jpg)
java web中的servlet3 upload上传文件实践
2021-07-09 08:33:28
C# XML基础入门小结(XML文件内容增删改查清)
2022-10-18 17:12:02
Mybatis注解实现多数据源读写分离详解
2021-12-15 21:44:16
![](https://img.aspxhome.com/file/2023/1/62211_0s.jpg)
Maven入门之使用Nexus搭建Maven私服及上传下载jar包
2022-05-06 20:47:43
![](https://img.aspxhome.com/file/2023/6/61656_0s.jpg)
mybatis Interceptor对UpdateTime自动处理的实现方法
2023-10-13 16:02:20
C#多线程系列之任务基础(一)
2022-12-09 04:48:22
使用java获取md5值的两种方法
2021-06-18 10:30:30
java使用jacob实现word转pdf
2023-05-12 11:45:33