問題描述
如何在 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?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!