首先,Spring的 WebMvcConfigurer
接口提供了很多方法让我们来定制SpringMVC的配置。
WebMvcConfigurerAdapter和WebMvcConfigurationSupport的区别
-
两个类都是来自包org.springframework.web.servlet.config.annotation
-
WebMvcConfigurationSupport是一个具体类,而WebMvcConfigurationAdapter则是一个抽象类
-
两个类都可以实现配置SpringMVC,即都可以配置视图解析器、拦截器以及静态资源等。
-
WebMvcConfigurerAdapter implements WebMvcConfigurer,所有方法实现都是空实现,且为抽象类,子类只需覆盖感兴趣的方法即可。
在 Spring5.0 开始,
WebMvcConfigurer
接口的所有方法都改为了默认方法(基于java8),所以就 不再需要WebMvcConfigurerAdapter类 了,也加上了@Deprecated,子类直接实现WebMvcConfigurer
即可。
- WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware。支持的自定义的配置更多更全,WebMvcConfigurerAdapter有的方法,这个类也都有。该类注释内容翻译:这是提供MVC Java config 背后配置的主要类。 通常是通过将@EnableWebMvc添加到应用程序的@Configuration类中来导入的。 另一个更高级的选择是直接从此类扩展并在需要时重写方法,记住子类要添加@Configuration,重写带有@Bean的方法也要加上@Bean。
@EnableWebMvc=WebMvcConfigurationSupport,使用了@EnableWebMvc注解等于扩展了WebMvcConfigurationSupport但是没有重写任何方法
另外,WebMvcConfigurationSupport(@EnableWebMvc)和@EnableAutoConfiguration这两种方式都有一些默认的设定。所以有以下几种使用方式:
- @Configuration + @EnableWebMvc + extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,但会使springboot的@EnableAutoConfiguration自动配置失效
- @Configuration + extends WebMvcConfigurationSupport,在扩展的类中重写父类的方法即可,但会使springboot的@EnableAutoConfiguration自动配置失效
- @Configuration + extends WebMvcConfigurationAdapter,在扩展的类中重写父类的方法即可,这种方式依旧使用springboot的@EnableAutoConfiguration中的设置
WebMvcConfigurationSupport类是彻底自定义配置springmvc,若容器中有该类的子类bean,则springboot的自动配置都会失效,因为WebMvcAutoConfiguration类有
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
方式1/2的源码分析
@EnableWebMvc
注解:- 有元注解
@Import(DelegatingWebMvcConfiguration.class)
。
- 有元注解
DelegatingWebMvcConfiguration
类:DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport
,后面分析该父类。- 有个
@Autowired
的方法setConfigurers(List<WebMvcConfigurer> configurers)
,获取Spring容器的所有WebMvcConfigurer
类型的bean(方式1的@Configuration + extends WebMvcConfigurationAdapter
注册的),存储到WebMvcConfigurerComposite
类型的configurers
属性中。 - 利用上面的
configurers
属性重写WebMvcConfigurationSupport
中所有的空方法(方式1)。
WebMvcConfigurationSupport
类:WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware
。- 有很多
@Bean
的方法,注入 SpringMVC 的一些关键组件,方法中会调用一些空方法,子类只需重写这些空方法就可以实现定制SpringMVC。(方式2)
方式3的源码分析
WebMvcConfigurerAdapter
:- 实现了
WebMvcConfigurer
接口,是抽象类,且所有方法都是空实现,子类需要重写自己感兴趣的方法。
- 实现了
WebMvcAutoConfiguration
(项目启动时自动执行):- 有元注解
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
,即只有当Spring容器中没有WebMvcConfigurationSupport
类型的bean时,该自动配置类才会生效。 - 定义一个内部静态类
WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter
,并注册一个该类的bean到Spring容器中。
- 有元注解
WebMvcAutoConfigurationAdapter
:@Import(EnableWebMvcConfiguration.class)
,注意EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration
。@EnableConfigurationProperties(WebMvcProperties.class)
,WebMvcProperties
绑定的是spring.mvc
开头的配置项。- 注册了很多SpringMVC的组件,且都有
@ConditionalOnMissingBean
,即当我们没有注册时才会自动注册,且都进行了默认设置,也会根据WebMvcProperties
的属性值进行设置。