spring - 是否可以有一个由星号定义的 @Value 属性?
问题描述
例如:
@Value("${a*}")
private Map<String, String> complexMap;
在我的application.yml
:
a*:
"a": "a"
"b": "b"
"c": "c"
我越来越Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'a*' in value "${a*}"
解决方案
首先,@Value 用于绑定到一个键。但是,如果该密钥有任何星号,它仍然有效并且可以正确读取。
例如:我们可以test*: hello
使用@Value 读取属性键。
@Value("${test1*}")
String greet; //hello
注意:我们应该使用@ConfigurationProperties
注释来读取多个键,在您的情况下,要读取 a Map<String, String>
,我们必须@ConfigurationProperties
在将其字段绑定到一堆属性的类上使用注释。因此,无论它是否具有星号字符,都不@Value
是绑定到 a 的正确用法。阅读地图的示例Map
即使有星号也可以阅读Map<String,String>
例子:
应用程序.yaml
test:
comp*:
a: a
b: b
地图属性.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
推荐阅读
- intellij-idea - IntelliJ 中的 Mocha 运行配置
- java - java.lang.ClassNotFoundException:在路径上找不到类“com.example.justjava.MainActivity”
- python - 任何人都可以解释 python 中 glob.glob() 函数的含义吗?
- javascript - 带有视频和图像问题的 bxslider
- javascript - 如果只有一个在 DOM 中呈现,则多个 HTML 相同的 id 元素
- angular - 从组件角度监听服务变量变化
- mysql - MYSQL:如何从第 3 行开始选择每 4 行?
- amazon-web-services - AWS ELB:如何查看启用 SSL 的 ELB 生成的出站网络流量字节数
- java - 需要数组但找到 int
- c# - 为什么发布视图时action方法的参数为null?