方式一:yaml中开启 refresh-enabled=true 时(默认开启),通过applicationContext.getEnvironment.getProperty 直接获取
方式二:standalone使用,@NacosValue获取最新值nacos配置信息需要写在配置类上
方式三:结合springcloud ,@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true
1.原生api
@SpringBootApplication
public class NacosConfigSimpleApplication {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext applicationContext =
SpringApplication.run(NacosConfigSimpleApplication.class, args);
//取到Spring的配置环境
while(true){
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String username = environment.getProperty("user.name");
String age = environment.getProperty("user.age");
System.out.println("username:"+username+" | age:"+age);
TimeUnit.SECONDS.sleep(1);
}
}
}
2.@NacosValue获取最新值
<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; }
}
3.@Value获取最新值 + @RefreshScope
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
yaml
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;
}
}