我有一个这样的属性文件:
- my.properties file:
- app.One.id=1
- app.One.val=60
- app.Two.id=5
- app.Two.val=75
我在Spring配置文件中将这些值读入我的bean中的map属性,如下所示:
- spring-config.xml:
- <bean id="myBean" class="myClass" scope="singleton">
- <property name="myMap">
- <map>
- <entry key="${app.One.id}" value="${app.One.val}"/>
- <entry key="${app.Two.id}" value="${app.Two.val}"/>
- </map>
- </property>
- </bean>
这样,如果我添加一个新的id / val到属性文件,我必须在config xml中添加一行,以便在myMap中有新的id / val.
我的问题是,有没有办法在spring配置文件中指定key-val对,以便xml中定义的key-val的数量可以找出属性文件中的项目并创建一个map.基本上我想在不同的环境中使用这个xml文件,我们在属性文件中使用不同数量的键值项.我只是不想在每个环境中更改xml文件以读取所有这些值.
如果您需要任何其他细节,请告诉我们任何想法/意见是赞赏.谢谢!
解决方法
这是使用Spring EL和自定义处理完成的.
尝试它是有趣的.有用 :)
application.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>
Utils.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;
- }
- }
Hello.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;
- }
- }
values.properties
- app.One.id=1
- app.One.val=60
- app.Two.id=5
- app.Two.val=75