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:
- 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).
- Create only a DispatcherServlet declaration in the web.xml and have one global ApplicationContext.
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.
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…