Có thể sử dụng Spring @Value không, để ánh xạ giá trị từ tệp thuộc tính vào HashMap?
Vâng, đúng vậy. Với một chút trợ giúp về mã và Spel.
Trước hết, hãy xem xét singleton mùa xuân-đậu này (bạn nên quét nó):
@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);
}
}
Lưu ý:PropertySplitter
lớp sử dụng Splitter
tiện ích từ ổi. Vui lòng tham khảo its documentation để biết thêm chi tiết.
Sau đó, trong một số đậu của bạn:
@Component
public class MyBean {
@Value("#{PropertySplitter.map('${service.expiration}')}")
Map<String, String> propertyAsMap;
}
Và cuối cùng, bất động sản:
service.expiration = name1:100,name2:20
Nó không chính xác những gì bạn đã hỏi, vì đây PropertySplitter
làm việc với một tài sản duy nhất mà được chuyển đổi thành một số Map
, nhưng tôi nghĩ bạn có thể chuyển sang cách chỉ định thuộc tính này hoặc sửa đổi mã PropertySplitter
để mã khớp với cách phân cấp hơn khao khát.
Nhà máy sản xuất đậu mới và mùa xuân là trực giao. phương tiện mới "no Spring" – duffymo
@duffymo không thể được khái quát hóa như thế. thực thể mới, ValueObject mới không có trong thuộc tính này – madhairsilence