如何注入 Spring application.properties 按前缀分组?
How to inject Spring application.properties grouped by prefix?
foo.bar.one=1
foo.bar.two=2
foo.bar.n=n
是否可以将 foo.bar.*
中的所有属性注入一个字段?
伪代码:
@Value("${foo.bar.*}")
private Map<String, Object> foobar;
使用@ConfigurationProperties("prefix")
(class水平)
所以在你的情况下:
@ConfigurationProperties("foo")
public class SomeClass {
private Map<String, Object> bar = new HashMap<>();; //the name of the map can serve as a second part of prefix
...
//dont forget getter that Spring will use to add values.
}
更多here
首先,不,你不能用@Value
做你想做的事。无论如何,您不应该使用 @Value
,至少一个原因是它不支持松散绑定。
其次,@ConfigurationProperties
会起作用,但您必须非常小心命名事物的方式。从字面上看你的例子,你需要:
@ConfigurationProperties(prefix = "foo")
public class Props {
private Map<String, String> bar = new HashMap<>();
public Map<String, String> getBar() {
return bar;
}
public void setBar(Map<String, String> bar) {
this.bar = bar;
}
}
注意名为 bar
的 prefix=foo
和 属性。
foo.bar.one=1
foo.bar.two=2
foo.bar.n=n
是否可以将 foo.bar.*
中的所有属性注入一个字段?
伪代码:
@Value("${foo.bar.*}")
private Map<String, Object> foobar;
使用@ConfigurationProperties("prefix")
(class水平)
所以在你的情况下:
@ConfigurationProperties("foo")
public class SomeClass {
private Map<String, Object> bar = new HashMap<>();; //the name of the map can serve as a second part of prefix
...
//dont forget getter that Spring will use to add values.
}
更多here
首先,不,你不能用@Value
做你想做的事。无论如何,您不应该使用 @Value
,至少一个原因是它不支持松散绑定。
其次,@ConfigurationProperties
会起作用,但您必须非常小心命名事物的方式。从字面上看你的例子,你需要:
@ConfigurationProperties(prefix = "foo")
public class Props {
private Map<String, String> bar = new HashMap<>();
public Map<String, String> getBar() {
return bar;
}
public void setBar(Map<String, String> bar) {
this.bar = bar;
}
}
注意名为 bar
的 prefix=foo
和 属性。