通常我们使用注解@EnableWebMvc
标注在@Configuration
注解的类上,用来初始化Spring MVC容器。如下所示 :
@Configuration
@EnableWebMvc
@ComponentScan(basePackageClasses = { MyConfiguration.class })
public class MyWebConfiguration {
}
https://docs.spring.io/spring/docs/4.3.15.RELEASE/spring-framework-reference/htmlsingle/#mvc-config-enable
上面的配置会注册一个RequestMappingHandlerMapping,一个RequestMappingHandlerAdapter和一个ExceptionHandlerExceptionResolver来提供注解控制器和注解方法(比如@RequestMapping和@ExceptionHandler等)处理请求的功能。
通过一个ConversionService实例,来进行Spring 3 方式的类型转换及数据绑定支持。
@NumberFormat格式化数字字段的支持
@DateTimeFormat格式化Date、Calendar、Long、JodaTime类型字段的支持。
如果检测到JSR-303 Bean验证的实现,在Controller方法上使用@Valid验证Bean。
一组HttpMessageConverter,用于在字符串和所需Java类型之间进行类型转换,等等。
实际上,@EnableWebMvc
仅仅导入一个类DelegatingWebMvcConfiguration
,DelegatingWebMvcConfiguration
继承自WebMvcConfigurationSupport
。WebMvcConfigurationSupport
提供缺省的Spring MVC配置,向容器注册一些mvc bean。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
而DelegatingWebMvcConfiguration
则增强了WebMvcConfigurationSupport
,它本身也是一个配置类,会被注入一组WebMvcConfigurer
,这组WebMvcConfigurer
会被DelegatingWebMvcConfiguration
用于定制Spring MVC配置。
@EnableWebMvc imports DelegatingWebMvcConfiguration, which:
Provides default Spring configuration for Spring MVC applications
Detects and delegates to WebMvcConfigurer implementations to customize that configuration.