Search code examples
javaspringspring-mvcresourcebundle

Programmatically refresh the spring mvc resource bundle


ResourceBundleMessageSource messages are configured in Spring's configuration file as

<bean id="messageSource"
  class="org.springframework.context.support.ResourceBundleMessageSource"
  p:basenames="WEB-INF/strings/appstrings" />

Whenever I changed any message in that properties file I have to restart server.

I want to read these updated messages programatically in my application without restarting server.

How can I read these messages programatically in one of my @Controller while running application.


Solution

  • Define your ResourceBundle property in applicationContext.xml file like:

    <!-- Message Source for appstrings -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="WEB-INF/strings/appstrings" />
    
    </bean>
    

    In you Java class/controller auto-wire it as:

    private ReloadableResourceBundleMessageSource messageSource;

      @Autowired
      public void setMessageSource(MessageSource messageSource) {
        this.messageSource = (ReloadableResourceBundleMessageSource) ((DelegatingMessageSource) messageSource).getParentMessageSource();
      }
    

    Then call clearCache() in any function in that class/controller.

    messageSource.clearCache();
    

    I got this exception in controller

    ReloadableResourceBundleMessageSource incompatible with org.springframework.context.support.DelegatingMessageSource
    

    When you try to run it through messageSource in your controller, you get NOTHING, empty string. And if you look closely, you will find that you have a DelegatingMessageSource in your messageSource property, with an empty parent source, which means it is EMPTY, i.e. always returns blank.

    Here’s the solution for this little challenge: move your messageSource definition from spring-servlet.xml to applicationContext.xml!

    Read more..