@Value
chú thích hoạt động trên phiên bản mới của mùa xuân (thử nghiệm trên v3.2.2) Sau đây là cách nó được thực hiện:
Bản đồ đệ tài sản của bạn trong tập tin cấu hình mùa xuân
<!--Import Info:
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd-->
<context:property-placeholder location="classpath:/app-config.properties" />
Tạo app-config.properties bên trong (gốc) thư mục nguồn của bạn
my.property=test
my.property2=test2
Tạo một lớp điều khiển
@Controller
public class XRDSBuilder
{
@Value("${my.property}")
private String myProperty;
public String getMyProperty() { return myProperty; }
}
mùa xuân sẽ tự động lập bản đồ các nội dung của tôi.tài sản để biến bạn bên trong bộ điều khiển
Mapping to a list
giá trị tài sản:
my.list.property=test,test2,test3
điều khiển lớp cấu hình:
@Value("#{'${my.list.property}'.split(',')}")
private List<String> myListProperty;
Advanced mapping
@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);
}
}
giá trị tài sản:
my.complex.property=test1:value1,test2:value2
điều khiển lớp:
@Value("#{PropertySplitter.map('${my.complex.property}')}")
Map<String, String> myComplexProperty;
Xem http: // stackoverflow.com/questions/5172392/how-to-programmatically-resolve-property-placeholder-in-spring. Có vẻ như có thể kể từ mùa xuân 3. – Vadzim