Quantcast
Viewing all articles
Browse latest Browse all 33

Programmatically refresh Spring mvc resource bundle

Programmatically refresh Spring mvc resource bundle OR Inject Spring ReloadableResourceBundleMessageSource OR Spring message translation found in JSP but not in controller

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();

This will work for sure and you can refresh you resource bundle message property file in container without refreshing server.

One thing to note is:

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.

I wrote this in spring-servlet.xml file and got this exception in controller

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

Well, here’s the thing:  Spring will setup a DelegatingMessageSource when it can’t find a message source definition.  What’s that, you say?  it DID find a message source, it found it for my View!  That’s true, it did find it for the view, but not for your controller.  Why is that?  I don’t really know, but fortunately, I know how to fix it Image may be NSFW.
Clik here to view.
:)

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

This will let Spring find your messageSource for your Controller as well, and all will be well.

Image may be NSFW.
Clik here to view.
Share


Viewing all articles
Browse latest Browse all 33

Trending Articles