作用:当配置类中添加了该注解了之后,就表示某个模块的自动配置就都失效了,全部都要自己配置

例如下面这个MVC模块的配置类

/**
 * @author:抱着鱼睡觉的喵喵
 * @date:2020/12/18
 * @description:
 */
//使用WebMvcConfigurer接口扩展Spring MVC的功能
@Configuration
@EnableWebMvc
public class MyMVcConfig implements WebMvcConfigurer {
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //向浏览器发送/hao请求来到success
        registry.addViewController("/hao").setViewName("forward:success");
    }
}

自此这段代码就表示SpringMVC的自动配置就都失效了


为了加一个@EableWebMvc注解,自动配置就都失效了呢?

原理如下:

ctrl+右键点击该注解查看源码

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

其中的DelegatingWebMvcConfiguration是核心-》继续进去查看源码
核心的代码如下

public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

我们发现这个类继承了WebMvcConfigurationSupport,那这和自动配置失效有什么联系呢?

重点来了

查看WebMvcAutoConfiguration ---- web模块自动配置类-》源码

头部代码如下

@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

其中的@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)是关键,它的意思是容器中没有WebMvcConfigurationSupport这个类时,自动配置类才会生效

所以我们就明白了,因为@EableConfiguration注解中的DelegatingWebMvcConfiguration继承了WebMvcConfigurationSupport,所以才会导致自动配置类失效


===========================================================
总结:
@EnableWebMvc将WebMvcConfigurationSupport组件导入容器里了,WebMvcConfigurationSupport里只有基础的功能

posted on 2020-12-18 18:55  凸凸大军的一员  阅读(148)  评论(0编辑  收藏  举报