Reading a dynamic property map into Spring managed bean

后端 未结 4 2115
悲哀的现实
悲哀的现实 2021-02-05 23:53

I have a properties file like this:

my.properties file:
app.One.id=1
app.One.val=60

app.Two.id=5
app.Two.val=75

And I read these values into a

4条回答
  •  时光取名叫无心
    2021-02-06 00:56

    This is done with Spring EL and custom handling.

    It was just interesting for me to try it. It works :)

    application.xml

    
    
        
    
        
            
        
    
    
    

    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 propsToMap(Properties props,
                String idPatternString, String valuePatternString) {
    
            Map map = new HashMap();
    
            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 map;
    
        public Map getMap() {
            return map;
        }
    
        public void setMap(Map map) {
            this.map = map;
        }
    }
    

    values.properties

    app.One.id=1
    app.One.val=60
    
    app.Two.id=5
    app.Two.val=75
    

提交回复
热议问题