如何使用@Value Spring Annotation 注入 Map?
如何在 Spring 中使用 @Value 注释从属性文件中将值注入 Map?
How can I inject values into a Map from the properties file using the @Value annotation in Spring?
我的 Spring Java 类是,我尝试使用 $,但收到以下错误消息:
My Spring Java class is and I tried using the $, but got the following error message:
无法自动装配字段:私有 java.util.Map Test.standard;嵌套异常是 java.lang.IllegalArgumentException:无法解析字符串值${com.test.standard}"中的占位符com.test.standard";
Could not autowire field: private java.util.Map Test.standard; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'com.test.standard' in string value "${com.test.standard}"
@ConfigurationProperty("com.hello.foo")
public class Test {
@Value("${com.test.standard}")
private Map<String,Pattern> standard = new LinkedHashMap<String,Pattern>
private String enabled;
}
我在 .properties 文件中有以下属性
I have the following properties in a .properties file
com.test.standard.name1=Pattern1
com.test.standard.name2=Pattern2
com.test.standard.name3=Pattern3
com.hello.foo.enabled=true
推荐答案
我相信 Spring Boot 支持通过 @ConfigurationProperties 注释.
I believe Spring Boot supports loading properties maps out of the box with @ConfigurationProperties annotation.
根据该文档,您可以加载属性:
According that docs you can load properties:
my.servers[0]=dev.bar.com
my.servers[1]=foo.bar.com
像这样变成豆子:
@ConfigurationProperties(prefix="my")
public class Config {
private List<String> servers = new ArrayList<String>();
public List<String> getServers() {
return this.servers;
}
}
我之前使用过@ConfigurationProperties 功能,但没有加载到地图中.您需要使用 @EnableConfigurationProperties 注释 以启用此功能.
I used @ConfigurationProperties feature before, but without loading into map. You need to use @EnableConfigurationProperties annotation to enable this feature.
这个功能很酷的地方在于你可以验证你的属性.
Cool stuff about this feature is that you can validate your properties.
相关文章