Spring MVC w/ no XML

Just a quick update: finally figured out how to setup Spring MVC without any XML during my lunch break.. Yeah, I’m a nerd like that. Spring for lunch.

Anywho, on to setup Spring MVC without XML (as in no applicationContext.xml file). There’s two approaches you can take:

  1. Configure a global ApplicationContext via the ContextLoaderListener that bootstraps Spring in the J2EE web.xml file (thus creating a primary bean container), as well as a second ApplicationContext configured by the DispatcherServlet (thus having a secondary / child bean container).
  2. Create only a DispatcherServlet declaration in the web.xml and have one global ApplicationContext.
I’ve found that having multiple bean containers often leads to Dependency Injection issues (with objects being out of scope or instantiated multiple times) so I often opt for option B. In the end, less code + less configuration = less bugs.

Per the JavaDoc of the DispatcherServlet‘s superclass, FrameworkServlet, this class looks for a servlet init-parameter of contextClass for a fully qualified class name to bootstrap your app. When no contextClass parameter is found, it defaults to an XML-powered Spring Context… yuck! Since we want to rely on Java’s type safety, we’ll provide the necessary info to delegate to AnnotationConfigWebApplicationContext and scan the packages in com.example:

And just like that, any @Configuration or @Component classes declared in your com.example packages & sub-packages will be evaluated at startup! Now all we need to do is configure out MVC components (and supply our application-specific @Controllers, obviously).

Luckily, Spring provides us with some nifty annotations and base-classes out of the box, so all we really need to do is create a configuration like the following:

After that, just supply your controllers and you’re off to the races. Things to note:

  • Not only did we tag our class with @Configuration, but we also tagged it with @EnableWebMvc & @ComponentScan to search for our @Controllers
  • We declared a ViewResolver with the commonly used InternalResourceViewResolver configured for use with JSPs stored in a sub-folder of our WEB-INF directory.
  • A subtle but important feature: our configuration extends WebMvcConfigurerAdapter (providing sensible defaults for our MVC app) and overrides the addResourceHandlers method to allow resources requested from /resources/to be served up by the servlet container (static resources like CSS, JavaScript, etc.)Note: there were API changes between Spring 3.1.0-M1 and 3.1.0-RELEASE regarding some of the methods on this class, so pay attention as you read about some of these new features.

 

Update: Not only did I figure out how to go XML-less, I also created a Maven archetype and am publishing it to the Sonatype OSS Repository Hosting, meaning you can start using it (and 1,500+ other Archetypes) with ease.

.. Details coming here shortly…