摘要:

  在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. 津门杯WriteUP

    最近很浮躁,好好学习 WEB power_cut 扫目录 index.php <?php class logger{ public $logFile; public $initMsg; publ ...

  2. LiteFlow 2.6.4版本发行注记,里程碑版本!

    一 这个版本做的很折腾.期间几个issue推翻重做了好几次. 但我最终还是带来了LiteFlow 2.6.4这个重要版本. 虽然版本是小版本号升级,但是带来的更新可一点也不少.并完全向下兼容. 如果你 ...

  3. c++学习笔记(十)

    返回应用类型 返回引用 1.不要返回局部变量的引用 为了验证为什么不能返回局部变量的引用,我按照所学的例题自己做了一点小测试. #include<iostream> using names ...

  4. Dapr-Actor构建块

    前言: 前篇-绑定 文章对Dapr的绑定构建块进行了解,本篇继续对 Actor 构建块进行了解学习. 一.Actor简介: Actors 为最低级别的"计算单元". 换句话说,您将 ...

  5. 深刻理解Spring声明式事务

    问题引入 Spring中事务传播有哪几种,分别是怎样的? 理解注解事务的自动配置? SpringBoot启动类为什么不需要加@EnableTransactionManagement注解? 声明式事务的 ...

  6. [atAGC049F]Happy Sequence

    定义$L=2\cdot 10^{5}$,$g(x)=\sum_{i=1}^{n}|b_{i}-x|-|a_{i}-x|$,则合法当且仅当$\forall 0\le x\le L,g(x)\ge 0$, ...

  7. 【NetWork】外网和内网

    外网和内网 2019-11-16  11:22:37  by冲冲 1.内网 ① 内网的电脑们,需要经过交换机.路由器,才能访问Internet(外网). ② 因为外网IP比较紧张,现在的电脑普及使得外 ...

  8. 【Design Patterns】(1)概述

    设计模式 -- 概述 2019-07-17  22:43:32  by冲冲 1. 简介 ① 设计模式 是软件开发人员在软件开发过程中,针对一般问题的最佳解决方案,该方案能够被程序员反复应用于解决类似问 ...

  9. springboot默认Thymeleaf模板引擎js的解决方案

    <script th:inline="javascript"> var btnexam=[[${btnexam}]]; console.log(btnexam); va ...

  10. Springboot .properties或.yml配置文件读取pom.xml文件值

    有时候配置文件需要读取pom文件配置<properties></properties>中间自定义属性值的时候可以用@@获取 例:@package.parameter@ 然后还需 ...