using properties within the properties file

前端 未结 5 1088
执念已碎
执念已碎 2020-12-17 02:14

I apologize for the title.. i couldn\'t find a better way to explain the situation.

I use to load properties file using a Property class as described in the URL http

5条回答
  •  感情败类
    2020-12-17 02:51

    I've done something like this and it isn't that difficult, you simply subclass the Properties class and implement your own getProperty method, check for a pattern and replace it if necessary.

    //this makes the pattern ${sometext}
    static public final String JAVA_CONFIG_VARIABLE = "\\$\\{(.*)\\}";
    
    @Override
    public String getProperty(String key)
    {
        String val = super.getProperty(key);
        if( val != null && val.indexOf("${") != -1 )
        {
            //we have at least one replacable parm, let's replace it
            val = replaceParms(val);
        }
        return val;
     }
    
     public final String replaceParms(String in)
     {
         if(in == null) return null;
         //this could be precompiled as Pattern is supposed to be thread safe
         Pattern pattern = Pattern.compile(JAVA_CONFIG_VARIABLE);
         Matcher matcher = pattern.matcher(in);
         StringBuffer buf = new StringBuffer();
         while (matcher.find())
         {
             String replaceStr = matcher.group(1);
             String prop = getProperty(replaceStr);   
             //if it isn't in our properties file, check if it is a system property
             if (prop == null )
                 prop = System.getProperty(replaceStr);
             if( prop == null )
             {
                System.out.printf("Failed to find property '%s' for '%s'\n", replaceStr, in);
             }
             else
             {
               matcher.appendReplacement(buf, prop);
             } 
         }
         matcher.appendTail(buf);
         String result = buf.toString();
         return result;
     }
    

提交回复
热议问题