0

Can we reuse the key values in Properties files something like below?

key1=hello
key2=#{key1} world!

thanks,


Update: Below is the code to override the ResourceBundle that turns key values reusable,

public class Messages extends ResourceBundle {

    public Messages() {
       setParent(getBundle("resources.test", FacesContext.getCurrentInstance().getViewRoot().getLocale()));
           }

    @Override
    public Enumeration<String> getKeys() {
         return parent.getKeys();
    }


    @Override
    protected Object handleGetObject(String key) {

        try {
               return replaceKey(parent, key, 3);
        } catch (Exception e) {        }
    try { return parent.getObject(key);
    } catch (MissingResourceException e) {
        return key;
    }
    catch (Exception e) {
        return key;
    }
}
    private Pattern Pattern = Pattern.compile("\\$\\{([\\w\\.\\-]+)\\}");

    private String replaceKey(ResourceBundle bundle, String key, int iteration) {
    String message = bundle.getString(key);
    if (message != null) {
      StringBuffer sb = new StringBuffer();
      Matcher matcher = Pattern.matcher(message);
      while (matcher.find() && iteration > 0) {
        // the magic
        matcher.appendReplacement(sb, replaceKey(bundle, matcher.group(1), iteration - 1));
      }
      matcher.appendTail(sb);
      return sb.toString();
    }
    return null;
  }

}

Please see below for refrence

Basic Implementation

Manuplation

Community
  • 1
  • 1
Jeyan
  • 729
  • 1
  • 14
  • 27

1 Answers1

1

That's only possible with a custom ResourceBundle wherein you override the handleGetObject() method to check if the retrieved bundle value doesn't contain some specific syntax which should be substituted with another bundle value accordingly.

Finally just register the custom ResourceBundle instead in the <resource-bundle> or <f:loadBundle>.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You can find a kickoff example in this answer: http://stackoverflow.com/questions/6451215/jsf-how-to-remove-the-surrounding-if-message-not-found-in-messagebundle/6452047#6452047 – BalusC Jul 28 '12 at 13:38