首页 技术 正文
技术 2022年11月14日
0 收藏 993 点赞 2,848 浏览 1659 个字

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

例如下面这个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里只有基础的功能

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294