springboot扩展SpringMVC
既保留自动配置又有扩展配置
根据官网的描述,如果想要扩展SpringBoot对于SpringMVC的配置而又保留SpringBoot对SpringMVC的自动配置,可以编写一个配置类(@Configuration)继承WebMvcConfigurerAdapter类,但是不能标注@EnableWebMvc
1 2 3 4 5 6 7 8
| @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter {
@Override public void addInterceptors(InterceptorRegistry registry) { super.addInterceptors(registry); } }
|
原因
为什么继承WebMvcConfigurerAdapter就可以扩展springmvc的配置呢?
在于WebMvcAutoConfiguration类中有一个bean是WebMvcAutoConfigurationAdapter
1 2 3 4
| @Configuration @Import(EnableWebMvcConfiguration.class) @EnableConfigurationProperties({ WebMvcProperties.class, ResourceProperties.class }) public static class WebMvcAutoConfigurationAdapter extends WebMvcConfigurerAdapter {
|
使用@Import来引入的这个组件中有一个方法,会将所有的WebMvcConfigurer类都加入到configurers中
1 2 3 4 5
| public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } }
|
而WebMvcConfigurerAdapter就实现于WebMvcConfigurer
1
| public abstract class WebMvcConfigurerAdapter implements WebMvcConfigurer {
|
使用自定义配置抛弃自动配置
需要在上述配置类上加上@EnableWebMvc注解,就可以完全取代springboot对于springmvc的自动配置
原因
至于为什么会这样,看一下@EnableWebMvc这个注解就知道了
1 2 3 4 5 6
| @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Import(DelegatingWebMvcConfiguration.class) public @interface EnableWebMvc { }
|
这个注解会引入一个DelegatingWebMvcConfiguration组件,而这个类是继承自WebMvcConfigurationSupport
1 2
| @Configuration public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
|
接下来看一下WebMvcAutoConfiguration的加载条件是什么
1 2 3 4 5 6 7 8 9
| @Configuration @ConditionalOnWebApplication @ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurerAdapter.class }) @ConditionalOnMissingBean(WebMvcConfigurationSupport.class) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10) @AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, ValidationAutoConfiguration.class }) public class WebMvcAutoConfiguration {
|
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
可以看到是在没有WebMvcConfigurationSupport这个bean的时候才会加载,所以打破了这个条件导致WebMvcAutoConfiguration不会生效