是否可以使用Spring @Value將屬性文件中的值映射到HashMap?
是的。有一點代碼和Spel的幫助。
首先,考慮這單春豆(你應該對其進行掃描):
@Component("PropertySplitter")
public class PropertySplitter {
/**
* Example: one.example.property = KEY1:VALUE1,KEY2:VALUE2
*/
public Map<String, String> map(String property) {
return this.map(property, ",");
}
/**
* Example: one.example.property = KEY1:VALUE1.1,VALUE1.2;KEY2:VALUE2.1,VALUE2.2
*/
public Map<String, List<String>> mapOfList(String property) {
Map<String, String> map = this.map(property, ";");
Map<String, List<String>> mapOfList = new HashMap<>();
for (Entry<String, String> entry : map.entrySet()) {
mapOfList.put(entry.getKey(), this.list(entry.getValue()));
}
return mapOfList;
}
/**
* Example: one.example.property = VALUE1,VALUE2,VALUE3,VALUE4
*/
public List<String> list(String property) {
return this.list(property, ",");
}
/**
* Example: one.example.property = VALUE1.1,VALUE1.2;VALUE2.1,VALUE2.2
*/
public List<List<String>> groupedList(String property) {
List<String> unGroupedList = this.list(property, ";");
List<List<String>> groupedList = new ArrayList<>();
for (String group : unGroupedList) {
groupedList.add(this.list(group));
}
return groupedList;
}
private List<String> list(String property, String splitter) {
return Splitter.on(splitter).omitEmptyStrings().trimResults().splitToList(property);
}
private Map<String, String> map(String property, String splitter) {
return Splitter.on(splitter).omitEmptyStrings().trimResults().withKeyValueSeparator(":").split(property);
}
}
注:PropertySplitter
類使用Splitter
實用番石榴。詳情請參閱its documentation。
然後,在你的一些豆:
@Component
public class MyBean {
@Value("#{PropertySplitter.map('${service.expiration}')}")
Map<String, String> propertyAsMap;
}
最後,屬性:
service.expiration = name1:100,name2:20
這不是你問什麼,因爲這PropertySplitter
作品與一個單一的屬性, 轉換成到Map
,但我認爲你可以切換到這種指定屬性的方式,或修改PropertySplitter
代碼,以便它匹配更多層次的方式慾望。
新和春豆廠是正交的。新的意思是「沒有彈簧」 – duffymo 2015-02-06 15:49:24
@duffymo不能這樣概括。新的實體,新的ValueObject不在此 – madhairsilence 2016-12-20 12:16:20