This post focuses on what's new for Spring MVC in Spring 3.1 M2. Here are the topics:
- Code-based equivalent for the MVC namespace.
- Customizable @MVC processing.
- Programming model improvements.
A brief reminder that the features discussed here are in action at the Greenhouse project.
Code-based Configuration For Spring MVC
As Chris pointed out in his blog post last Friday, XML namespaces cut down configuration dramatically but also reduce transparency and sometimes flexibility. This holds true for the MVC namespace, which supports a number of customizations but not everything that's available. That means you are either able to use it or otherwise leave it. We believe code-based configuration has a solution for that and a path from simple to advanced.
Let's begin with this simple, familiar snippet:
<mvc:annotation-driven />
Although not required for using annotated controllers, <mvc:annotation-driven>
does a number of useful things -- it detects the presence of a JSR-303 (Bean Validation) implementation and configures data binding with it, it adds a JSON message converter if Jackson JSON library is available, and a few other things that can save quite a bit of configuration.
Now let's match that with code-based configuration:
@Configuration
@EnableWebMvc
public class WebConfig {
}
Here @EnableWebMvc
imports an @Configuration
class that matches the goodness of <mvc:annotation-driven>
. As simple as that.
The next step is to use an attribute in <mvc:annotation-driven>
perhaps to provide a FormattingConversionService
, or to add a sub-element perhaps configuring message converters, or to use other MVC namespace elements like <mvc:interceptors>
, <mvc:resources>
, etc.
Let's see how to do all of that in code-based configuration:
@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
// register converters and formatters...
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// add message converters...
}
@Override
public void configureInterceptors(InterceptorConfigurer configurer) {
configurer.addInterceptor(new…