本文分析所用源代码基于
Spring 5.1.3 RELEASE
概述
通常我们使用注解@EnableWebMvc
在一个@Configuration
注解的配置类上,用于对Spring MVC
进行配置。用法如下所示 :
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
// 根据需求,重写 WebMvcConfigurer 接口所定义的各个方法从而定制Spring MVC
@Override
public void configureDefaultServletHandling(final DefaultServletHandlerConfigurer configurer) {
// ...
}
// ...
}
那么@EnableWebMvc
注解到底是怎么工作的 ?
实际上,@EnableWebMvc
仅仅导入一个类DelegatingWebMvcConfiguration
,而DelegatingWebMvcConfiguration
则继承自WebMvcConfigurationSupport
。WebMvcConfigurationSupport
的作用是提供缺省的Spring MVC
配置,具体体现形式是向容器登记一组Spring MVC
运行时使用的bean
。
而DelegatingWebMvcConfiguration
则增强了WebMvcConfigurationSupport
,它本身也是一个配置类,会被注入一组WebMvcConfigurer
,这组WebMvcConfigurer
会被DelegatingWebMvcConfiguration
用于定制Spring MVC
配置。
所以如果想对WebMvcConfigurationSupport
对Spring MVC
的缺省配置进行定制,可以让@EnableWebMvc
所注解的配置类实现接口WebMvcConfigurer
所定义的方法。也就是我们上面例子所演示的做法。
源代码
package org.springframework.web.servlet.config.annotation;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
// 使用注解@Import 引入代理配置类 DelegatingWebMvcConfiguration
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
作为一个注解,@EnableWebMvc
的代码并不复杂,可以看出,其主要的作用是通过@Import
注解导入Spring MVC
代理配置类DelegatingWebMvcConfiguration
。
总结
从上可见,@EnableWebMvc
注解的主要作用是引入DelegatingWebMvcConfiguration
配置类。而对Spring MVC
配置的主要工作,由WebMvcConfigurationSupport
和用户提供的WebMvcConfigurer
配置器实现。