Spring MVC and JSTL MessageSource Configuration

I’ve been working on a new web application over the last month whenever I can find some spare time.   I had initially started the project using Grails, but I had difficulty getting past the scaffolding.   Besides, my reading seems to always come back to Grails performance issues so I figured I’d just start with a tried & true Java Enterprise stack:  Spring, Hibernate, Spring MVC, and MySQL.

I spent the last few weeks dealing with the model, DAO, service, and controller layers.   I’m aiming for a solid RESTful API consuming and producing JSON from the onset.  I got all that to work seemingly well and am now actually ready to focus on views so I wrote my first JSP in about 10 years yesterday:

    <%@ include file="taglibs.jsp"%>
    <head>
        <title><fmt:message key="home.title"/></title>
    </head>
    <body class="home">
        <fmt:message key="home.heading"/>
    </body>

Now in my maven /src/main/resources directory, I have a message.properties file containing the following:

    home.properties=Home
    home.heading=Hello World!

Finally, I added the following to my MVC Configuration file (I’m using JavaConfig as opposed to the old school Spring XML):

    @Bean
    public MessageSource getMessageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("messages");
        return source;
    }

Not really any rocket science here, folks… This is pretty much standard based on the Spring documentation and about half a dozen blog entries.   The only difference with my configuration and what I found online was that the MessageSource was being configured using XML.

I spent several hours trying to get this to work but the view would render with ???home.title??? and ???home.heading??? and I couldn’t for the life of me figure out what the problem was.   I know that the bean was getting instantiated because I added a breakpoint there…   Finally I tried actually retrieving the MessageSource bean in the controller from the ApplicationContext.   Instead, I got a big fat exception that the bean was not found.    So I changed my configuration to retrieve the bean by name instead of by class:

    @Bean(name="messageSource")
    public MessageSource getMessageSource() {
         ResourceBundleMessageSource source = new ResourceBundleMessageSource():
         source.setBasename("messages"):
         return source;
     }

Just like magic, the JSP view now rendered just fine! Simply naming the bean ‘messageSource’ resolved a problem I had been tackling for several hours. I realize this blog doesn’t have an insane amount of traffic, but hopefully this will help somebody who runs into the same problem I did.