Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring引导合并配置属性_Java_Spring_Spring Boot - Fatal编程技术网

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好的,现在重试。已打开。