@NacosValue(value = "#{'${a:}'.empty ? '${b:}' : '${a:}'}", autoRefreshed = true)
private String value;
这样就实现了a属性如果为空的话 那么就用b属性的值
但是这样autoRefresh情况会有问题 只有第一个${}中的属性(a属性)改变才会动态刷新值 这个要注意

我定位到com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#onApplicationEvent 方法就是刷新@NacosValue的值的处理逻辑可以看到
a属性修改绑定的是#{'${a}'.empty ? '${b:}' : '${a:}'}和${a}表达式
b属性修改绑定的是#{'${b}'.empty ? '${a:}' : '${b:}'}和#{'${b}'.empty ? '${a:}' : '${c:}'}和${b}表达式
绑定值的确定逻辑可以看com.alibaba.nacos.spring.context.annotation.config.NacosValueAnnotationBeanPostProcessor#resolvePlaceholder 方法
private String resolvePlaceholder(String placeholder) {
//没有${或者#{的表达式 没有闭合} 返回null
if (!placeholder.startsWith("${") && !placeholder.startsWith("#{")) {
return null;
} else if (!placeholder.endsWith("}")) {
return null;
} else if (placeholder.length() <= "${".length() + "}".length()) {
return null;
} else {
//获取第一个${}中的值
int beginIndex = placeholder.indexOf("${");
if (beginIndex == -1) {
return null;
} else {
beginIndex += "${".length();
int endIndex = placeholder.indexOf("}", beginIndex);
if (endIndex == -1) {
return null;
} else {
placeholder = placeholder.substring(beginIndex, endIndex);
int separatorIndex = placeholder.indexOf(":");
return separatorIndex != -1 ? placeholder.substring(0, separatorIndex) : placeholder;
}
}
}
}
所以这个永远是第一个${}中的值刷新了才会刷新值
博客主要讨论了属性值动态刷新的问题,当a属性为空时用b属性值替代。指出autoRefresh情况下只有第一个${}中的属性(a属性)改变才会动态刷新值,还定位到刷新@NacosValue值的处理逻辑方法,以及绑定值确定逻辑的方法。
171万+

被折叠的 条评论
为什么被折叠?



