使用官方的nacos搭建对应的环境进行测试时,通常涉及到动态配置项
,都会使用nacos的配置中心
实现。
通常的做法,都是采取@RefreshScope
注解结合@Value
注解实现动态配置
、变更自动刷新
。
但在公司自己封装的nacos组件中进行测试,会出现Could not resolve placeholder 'XXXX' in string value "${xxx.xxx.xxx}
的报错信息,导致项目启动失败!
每次写@RefreshScope
和@Value
,都很麻烦。
@Value
可以使用表达式,给定默认值,这个是一个亮点!
此处为了代码的更好阅读性,使用@ConfigurationProperties
以bean的形式
来管理配置属性项。
kettle:
environment: dev
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = KettleProperties.PREFIX)
public class KettleProperties {
public static final String PREFIX = "kettle";
private String environment;
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
}
这里需要注意几点:
-
拼接。
如:private String envPath 时,nacos中的对应配置列为
kettle.env-path: 99999
get
方法!
在使用处,需要采取getxx获取变更项
如写一个controller
,测试获取变更属性。
@RestController
@Api(tags = "test")
@RequestMapping("/test")
public class TestController {
@GetMapping("/test")
public String test(){
return "998887654321";
}
@Autowired
KettleProperties kettleProperties;
@RequestMapping("/test3")
public String test3(){
return kettleProperties.getEnvironment() + "######";
}
}
分别在项目启动后,进行请求测试。
和修改nacos中对应的配置项后,再次请求测试。
可以发现能够随着nacos配置中心中的变更及时变更!
@ConfigurationProperties
使用时,针对属性,必须写get
!