How to inject a Map using the @Value Spring Annotation?(如何使用@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.
这篇关于如何使用@Value Spring Annotation 注入 Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用@Value Spring Annotation 注入 Map?


基础教程推荐
- 多个组件的复杂布局 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 从 python 访问 JVM 2022-01-01
- Java Swing计时器未清除 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01