Search code examples
javajsf-2resourcebundle

Reusing key values in Properties file by overriding ResourceBundle


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


Solution

  • 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>.