首先,@Value 用于绑定一个键。但是,如果该密钥有任何星号,它仍然有效且可以正确读取。
例如:我们可以使用@Value 读取属性键test*: hello。
@Value("${test1*}")
String greet; //hello
注意:我们应该使用@ConfigurationProperties 注释来读取多个键,在您的情况下,要读取Map<String, String>,我们必须在绑定其的类上使用@ConfigurationProperties 注释字段到一堆属性。所以在这里,@Value 不是绑定到Map 的正确用法,无论它是否具有星号字符。 Example For reading a Map
即使带有星号,也可以读取Map<String,String>
示例:
application.yaml
test:
comp*:
a: a
b: b
MapProperties.java
@Component
@ConfigurationProperties(prefix = "test")
public class MapProperties {
Map<String, String> comp;
public Map<String, String> getComp() {
return comp;
}
public void setComp(Map<String, String> comp) {
this.comp = comp;
}
}
这里,comp* 属性绑定到 MapProperties 类中的这个 comp 字段。
现在,您可以在需要的任何地方自动装配此 MapProperties 类
@Autowired
MapProperties mapProperties;
你可以通过调用它的getter方法来获取属性值:
mapProperties.getComp()
注意:如果没有这个前缀,它就不起作用,在我们的例子中,test。如果没有前缀,我们必须指定 @ConfigurationProperties(value= "comp*")
它抛出一个错误:
Configuration property name 'comp*' is not valid:
Invalid characters: '*'
Bean: mapProperties
Reason: Canonical names should be kebab-case ('-' separated), lowercase alpha-numeric characters and must start with a letter