摘要:

  在spring boot中 MVC这部分也有默认自动配置,也就是说我们不用做任何配置,那么也是OK的,这个配置类就是 WebMvcAutoConfiguration,但是也时候我们想设置自己的springMvc配置怎么办呢 。我们也可以写个自己的配置类,继承 WebMvcConfigurer 重写需要的配置方法 。在spring boot 早期是继承WebMvcConfigurerAdapter ,但是高版已标上注解@Deprecated,注意:在配置类中不要标注:@EnableWebMvc,否则,spring boot的配置全部失效,只留自己扩展配置。

示例:

这里已高版为主 继承WebMvcConfigurer,WebMvcConfigurer 接口中的方法都是默认的方法,可以覆盖,也可以不实现 ,加一个视图解析配置 ,解析success请求路劲,返回success页面。如下代码:

@Configuration
public class MyMvcConfig Implements WebMvcConfigurer { @Override
public void addViewControllers(ViewControllerRegistry registry) {
// super.addViewControllers(registry);
//浏览器发送 /success请求来到 success
registry.addViewController("/success").setViewName("success");
}
}
 

代码浅析:

1.首先我们来看看WebMvcAutoConfiguration这个配置类,这个配置了有首页的默认路劲,还有一些静态资源路劲,而这些方法在它的一个内部类中,如下代码(删除了部分代码):


@Configuration
@ConditionalOnWebApplication(
type = Type.SERVLET
)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class})
@ConditionalOnMissingBean({WebMvcConfigurationSupport.class})
@AutoConfigureOrder(-2147483638)
@AutoConfigureAfter({DispatcherServletAutoConfiguration.class, TaskExecutionAutoConfiguration.class, ValidationAutoConfiguration.class})
public class WebMvcAutoConfiguration {
....//省略部分代码
@Configuration
@Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class}) // 导入了EnableWebMvcConfiguration这个类 addResourceHandlers方法
@EnableConfigurationProperties({WebMvcProperties.class, ResourceProperties.class})
@Order(0)
public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ResourceLoaderAware {
  
    ...//省略部分代码
public void addResourceHandlers(ResourceHandlerRegistry registry) {//实现WebMvcConfigurer 这个类的
if(!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
} else {
Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
if(!registry.hasMappingForPattern("/webjars/**")) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"}).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
} String staticPathPattern = this.mvcProperties.getStaticPathPattern();
if(!registry.hasMappingForPattern(staticPathPattern)) {
this.customizeResourceHandlerRegistration(registry.addResourceHandler(new String[]{staticPathPattern}).addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations())).setCachePeriod(this.getSeconds(cachePeriod)).setCacheControl(cacheControl));
} }
} }
可以看到,内部类 WebMvcAutoConfigurationAdapter 标记 @Configuration,并导入另一个内部类 @Import({WebMvcAutoConfiguration.EnableWebMvcConfiguration.class}),我们看下这个类,如下代码:
@Configuration
public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
private final WebMvcProperties mvcProperties;
private final ListableBeanFactory beanFactory;
private final WebMvcRegistrations mvcRegistrations;
    ...// 省略
}
重点在它的父类, DelegatingWebMvcConfiguration  代码如下 (写了几个案列方法,其他代码省略。)。
@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); ...//省略
/**
* 从容器中拿到所有 WebMvcConfigurer 的实现类。遍历添加到 configurers
* [required description]
* @type {[type]}
*/
@Autowired( required = false ) // 自动装配
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if(!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
} }
...//省略
/**
* 当调用addResourceHandlers 时 ,调用的 成员configurers的 addResourceHandlers
* [addResourceHandlers description]
* @param {[type]} ResourceHandlerRegistry registry [description]
*/
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
this.configurers.addResourceHandlers(registry);
}
...//省略
}
来看看 WebMvcConfigurerComposite 的 addResourceHandlers的方法做了什么 :
class WebMvcConfigurerComposite implements WebMvcConfigurer {

    private final List<WebMvcConfigurer> delegates = new ArrayList<WebMvcConfigurer>();

    @Override
public void addViewControllers(ViewControllerRegistry registry) { // 遍历 把 所有WebMvcConfigurer的 addViewControllers方法调用一遍
for (WebMvcConfigurer delegate : this.delegates) {
delegate.addViewControllers(registry);
}
}
}
看到这里我们知道 ,不管是spring boot中实现的 WebMvcConfigurer 类,还是我们自己实现 WebMvcConfigurer ,只要我们把实现类注入到容器中,就会被 注入 WebMvcConfigurerComposite 这个类成员变量 delegates中
。而 WebMvcConfigurerComposite 有是实现了 WebMvcConfigurer  。当调用 WebMvcConfigurer中 xxx方法的,就会遍历 delegates 中所有 WebMvcConfigurer  的方法xxx 。那我们的扩展配置
MyMvcConfig 也就被调用了。


spring boot springMVC扩展配置 。WebMvcConfigurer ,WebMvcConfigurerAdapter的更多相关文章

  1. spring boot中扩展spring mvc 源码分析

    首先,确认你是对spring boot的自动配置相关机制是有了解的,如果不了解请看我spring boot相关的源码分析. 通常的使用方法是继承自org.springframework.boot.au ...

  2. 使用Spring Session实现Spring Boot水平扩展

    小编说:本文使用Spring Session实现了Spring Boot水平扩展,每个Spring Boot应用与其他水平扩展的Spring Boot一样,都能处理用户请求.如果宕机,Nginx会将请 ...

  3. 【转】spring boot application.properties 配置参数详情

    multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...

  4. Spring Boot 外部化配置(一)- Environment、ConfigFileApplicationListener

    目录 前言 1.起源 2.外部化配置的资源类型 3.外部化配置的核心 3.1 Environment 3.1.1.ConfigFileApplicationListener 3.1.2.关联 Spri ...

  5. Spring Boot 外部化配置(二) - @ConfigurationProperties 、@EnableConfigurationProperties

    目录 3.外部化配置的核心 3.2 @ConfigurationProperties 3.2.1 注册 Properties 配置类 3.2.2 绑定配置属性 3.1.3 ConfigurationP ...

  6. Spring Boot Redis 集成配置(转)

    Spring Boot Redis 集成配置 .embody{ padding:10px 10px 10px; margin:0 -20px; border-bottom:solid 1px #ede ...

  7. Spring Boot的自动配置原理及启动流程源码分析

    概述 Spring Boot 应用目前应该是 Java 中用得最多的框架了吧.其中 Spring Boot 最具特点之一就是自动配置,基于Spring Boot 的自动配置,我们可以很快集成某个模块, ...

  8. spring boot web相关配置

    spring boot集成了servlet容器,当我们在pom文件中增加spring-boot-starter-web的maven依赖时,不做任何web相关的配置便能提供web服务,这还得归于spri ...

  9. 初识Spring Boot框架(二)之DIY一个Spring Boot的自动配置

    在上篇博客初识Spring Boot框架中我们初步见识了SpringBoot的方便之处,很多小伙伴可能也会好奇这个Spring Boot是怎么实现自动配置的,那么今天我就带小伙伴我们自己来实现一个简单 ...

随机推荐

  1. airflow redis sentinel

    获取master name subscribe __sentinel__:hello mysql plugin table not found mysqld --initialize-insecure ...

  2. go微服务框架Kratos笔记(六)链路追踪实战

    什么是链路追踪 借用阿里云链路追踪文档来解释 分布式链路追踪(Distributed Tracing),也叫 分布式链路跟踪,分布式跟踪,分布式追踪 等等,它为分布式应用的开发者提供了完整的调用链路还 ...

  3. 菜鸡的Java笔记第二 - java 数据类型

    1.程序的本质实际上就是在于数据的处理上. JAVA中的数据类型有两类 基本数据类型:是进行内容的操作而不是内存的操作 数值型: 整型:byte(-128 ~ 127),short(-32768 ~ ...

  4. Node常用内置模块

    node内置的fs模块就是文件系统模块,负责读写文件 fs同时提供了同步异步的方法 'use strict'; var fs = require('fs'); fs.readFile('test.tx ...

  5. linux安全 设置登录失败次数后,拒绝登录

    设置登录失败3次后锁定用户300秒可以通过配合文件/etc/pam.d/sshd配置如下 在第一行 #%PAM-1.0 的下一行添加1a auth required pam_tally2.so den ...

  6. AnnotationConfigApplicationContext(1)之初始化Scanner和Reader

    AnnotationConfigApplicationContext(1)初始化Scanner和Reader 我们以AnnotationConfigApplicationContext为起点来探究Sp ...

  7. win8中让cmd.exe始终以管理员身份运行

    最近在学习配置本地服务器,在命令行启动mysql时总是由于权限不足而失败, Win+R -- cmd ,这样总是不能,还要找到cmd.exe右键以管理员身份运行cmd,再 net start mysq ...

  8. Cortex-A系列中断

    1. 回顾STM32系统 1.1 中断向量表 ARM芯片冲0x00000000,在程序开始的地方存放中断向量表,按下中断时,就相当于告诉CPU进入的函数.描述很多个中断服务函数的表. 对于STM32来 ...

  9. JS 执行上下文的一次理解

    执行上下文 执行上下文概念 当代码运行时,会产生一个对应的执行环境,在这个环境中,变量会被事先提出来(变量提升),代码从上往下开始执行,就叫做执行上下文. 注:在定义变量是未直接赋值,使用默认值 un ...

  10. 富集分析DAVID、Metascape、Enrichr、ClueGO

    前言 一般我们挑出一堆感兴趣的基因想临时看看它们的功能,需要做个富集分析.虽然公司买了最新版的数据库,如KEGG,但在集群跑下来嫌麻烦.这时网页在线或者本地化工具派上用场了. DAVID DAVID地 ...