Spring 注解 @EnableWebMvc 工作原理

通常我们使用注解@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继承自WebMvcConfigurationSupportWebMvcConfigurationSupport提供缺省的Spring MVC配置,向容器注册一些mvc bean。

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

DelegatingWebMvcConfiguration则增强了WebMvcConfigurationSupport,它本身也是一个配置类,会被注入一组WebMvcConfigurer,这组WebMvcConfigurer会被DelegatingWebMvcConfiguration用于定制Spring MVC配置。

spring官方文档

@EnableWebMvc imports DelegatingWebMvcConfiguration, which:
Provides default Spring configuration for Spring MVC applications
Detects and delegates to WebMvcConfigurer implementations to customize that configuration.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值