这是通过 Spring EL 和自定义处理完成的。
尝试一下对我来说很有趣。有用 :)
应用程序.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.1.xsd
">
<util:properties id="values" location="values.properties" />
<bean id="hello" class="my.Hello">
<property name="map"
value="#{T(my.Utils).propsToMap(values, '^(app\.\w*)\.id$', '{idGroup}.val')}" />
</bean>
</beans>
实用程序.java
package my;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
public static Map<String, String> propsToMap(Properties props,
String idPatternString, String valuePatternString) {
Map<String, String> map = new HashMap<String, String>();
Pattern idPattern = Pattern.compile(idPatternString);
for (Enumeration<?> en = props.propertyNames(); en.hasMoreElements();) {
String key = (String) en.nextElement();
String mapKey = (String) props.getProperty(key);
if (mapKey != null) {
Matcher idMatcher = idPattern.matcher(key);
if (idMatcher.matches()) {
String valueName = valuePatternString.replace("{idGroup}",
idMatcher.group(1));
String mapValue = props.getProperty(valueName);
if (mapValue != null) {
map.put(mapKey, mapValue);
}
}
}
}
return map;
}
}
你好.java
package my;
import java.util.Map;
public class Hello {
private Map<String, String> map;
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
值.属性
app.One.id=1
app.One.val=60
app.Two.id=5
app.Two.val=75