本文分析所用源代码基于
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配置器实现。
本文深入探讨了SpringMVC中@EnableWebMvc注解的工作原理。该注解通过导入DelegatingWebMvcConfiguration类来定制SpringMVC配置,允许用户通过实现WebMvcConfigurer接口来进一步调整配置。
5万+

被折叠的 条评论
为什么被折叠?



