如何在 Spring 中使用 @Value 注释将值从属性文件注入到 Map 中?
我的 Spring Java 类是,我尝试使用 $,但收到以下错误消息:
无法自动装配字段:private java.util.Map Test.standard;嵌套异常是 java.lang.IllegalArgumentException:无法解析字符串值“${com.test.standard}”中的占位符“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 文件中有以下属性
com.test.standard.name1=Pattern1
com.test.standard.name2=Pattern2
com.test.standard.name3=Pattern3
com.hello.foo.enabled=true
原文由 yathirigan 发布,翻译遵循 CC BY-SA 4.0 许可协议
我相信 Spring Boot 支持使用 @ConfigurationProperties 注释开箱即用地加载属性映射。
根据该文档,您可以加载属性:
像这样变成豆子:
我之前使用过 @ConfigurationProperties 功能,但没有加载到地图中。您需要使用 @EnableConfigurationProperties 注释 来启用此功能。
此功能的妙处在于您可以 验证您的属性。