How do I avoid repetition in Java ResourceBundle strings?

后端 未结 2 944
名媛妹妹
名媛妹妹 2021-02-05 15:09

We had a lot of strings which contained the same sub-string, from sentences about checking the log or how to contact support, to branding-like strings containing the company or

2条回答
  •  旧巷少年郎
    2021-02-05 15:16

    I think this is a fundamental flaw in the way ResourceBundles are designed to function: keys that reference other keys automatically violate the DRY (don't repeat yourself) principle. The way I got around this was similar to your method: create a ReflectiveResourceBundle class that allows you to specify Resource keys in the messages using EL notation.

    THE WRONG WAY:

    my.name.first=Bob
    my.name.last=Smith
    my.name.full=Bob Smith
    

    THE RIGHT WAY:

    my.name.first=Bob
    my.name.last=Smith
    my.name.full=${my.name.first} ${my.name.last}
    

    I've uploaded the code to GitHub so you or anyone else can download it. Additionally, I've added some sample code for anyone using the Stripes Framework (http://www.stripesframework.org/) to get you quickly up-and-running.

    The trick to getting this to work with standard JSTL fmt taglibs was to set up an interceptor that replaced the HttpServletRequest's resource with our own. The code looks something like this:

    ResourceBundle bundle = MyStaticResourceHoldingTheBundle.getBundle();
    Config.set(request, Config.FMT_LOCALIZATION_CONTEXT, new LocalizationContext(bundle, locale));
    

    Take a look at the stripes.interceptor package in the link above for more details.

提交回复
热议问题