Java Spring引导合并配置属性
我有一个用例,需要基于两个前缀绑定配置属性,其中一个前缀在运行时确定。假设常量前缀为Java Spring引导合并配置属性,java,spring,spring-boot,Java,Spring,Spring Boot,我有一个用例,需要基于两个前缀绑定配置属性,其中一个前缀在运行时确定。假设常量前缀为foo,运行时前缀为bar 给定JavaBean类的新实例FooBar,代码应该绑定所有环境变量FOO,然后用所有环境变量BAR覆盖 有一种方法可以将前缀动态绑定到类,正如我在(下面显示的示例代码)中所述。然而,缺少的是结果的合并 var bindable = Bindable.of(FooBar.class); var properties = ConfigurationPropertySources.get(
foo
,运行时前缀为bar
给定JavaBean类的新实例FooBar
,代码应该绑定所有环境变量FOO
,然后用所有环境变量BAR
覆盖
有一种方法可以将前缀动态绑定到类,正如我在(下面显示的示例代码)中所述。然而,缺少的是结果的合并
var bindable = Bindable.of(FooBar.class);
var properties = ConfigurationPropertySources.get(env);
new Binder(properties)
.bind("prefix", bindable)
.orElse(new FooBar());
示例:
public class FooBar {
private Duration latency = Duration.ofMillis(500L);
// other properties
// getters, setters
}
如果没有环境变量FOO_LATENCY
或BAR_LATENCY
,FooBar.getLatency()
为500毫秒。如果只有FOO_LATENCY
和BAR_LATENCY
中的一个存在,则FooBar.getLatency()
取其值。如果同时存在FOO\u LATENCY
和BAR\u LATENCY
,则FooBar.getLatency()
取BAR\u LATENCY
的值
你知道怎么做吗?更新了 只需再次调用
bind
。它仅分配在配置属性中找到的值,并且最后一个前缀绑定将根据每个属性赢得
范例
class FooBar{
私人字符串a;
私有字符串b=“b”;
私有字符串c;
私有字符串d;
私有字符串e=“e”;
//盖特、塞特和托斯特林在这里
}
属性(YAML)
你好
x、 b:世界
z、 a:再见
z、 c:测试
试验
Binder=Binder.get(env);
FooBar FooBar=新FooBar();
系统输出打印项次(fooBar);
fooBar=binder.bind(“x”,Bindable.ofInstance(fooBar)).orElse(fooBar);
系统输出打印项次(fooBar);
fooBar=binder.bind(“y”,Bindable.ofInstance(fooBar)).orElse(fooBar);
系统输出打印项次(fooBar);
fooBar=binder.bind(“z”,Bindable.ofInstance(fooBar)).orElse(fooBar);
系统输出打印项次(fooBar);
输出
FooBar[a=null,b=b,c=null,d=null,e=e]
FooBar[a=Hello,b=World,c=null,d=null,e=e]
FooBar[a=Hello,b=World,c=null,d=null,e=e]
FooBar[a=再见,b=世界,c=测试,d=null,e=e]
如您所见,第三个绑定覆盖第一个绑定的值,但仅覆盖实际配置的属性,这就是第二个绑定不做任何操作的原因
我还简化了逻辑,跳过了
ConfigurationPropertySources.get()
您的测试是错误的,因为您总是同时指定foo
和bar
。从属性中删除bar
,设置FooBar.b=“blah”
,然后查看第二次得到的结果。@AbhijitSarkar确保它有效。我已经更新了示例以包含默认值。没有,我已经更新了注释以指出问题。@AbhijitSarkar好的,现在重试。已打开。