前言
SpringBoot 对我们的 SpringMVC 还做了哪些配置,我们如何扩展,如何定制?
官网阅读地址:官方文档
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48Spring MVC Auto-configuration
// Spring Boot 为 Spring MVC 提供了自动配置,它可以很好地与大多数应用程序一起工作。
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
// 自动配置在 Spring 默认设置的基础上添加了以下功能:
The auto-configuration adds the following features on top of Spring’s defaults:
// 包含视图解析器
Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.
// 支持静态资源文件夹的路径,以及 webjars
Support for serving static resources, including support for WebJars
// 自动注册了 Converter:
// 转换器,这就是我们网页提交数据到后台自动封装成为对象的东西,比如把"1"字符串自动转换为 int 类型
// Formatter:【格式化器,比如页面给我们了一个 2019-8-10,它会给我们自动格式化为 Date 对象】
Automatic registration of Converter, GenericConverter, and Formatter beans.
// HttpMessageConverters
// SpringMVC 用来转换 Http 请求和响应的的,比如我们要把一个 User 对象转换为 JSON 字符串,可以去看官网文档解释;
Support for HttpMessageConverters (covered later in this document).
// 定义错误代码生成规则的
Automatic registration of MessageCodesResolver (covered later in this document).
// 首页定制
Static index.html support.
// 图标定制
Custom Favicon support (covered later in this document).
// 初始化数据绑定器:帮我们把请求数据绑定到 JavaBean 中!
Automatic use of a ConfigurableWebBindingInitializer bean (covered later in this document).
/*
如果您希望保留 Spring Boot MVC 功能,并且希望添加其他 MVC 配置(拦截器、格式化程序、视图控制器和其他功能),
则可以添加自己的@configuration 类,类型为 webmvcconfiguer,但不添加@EnableWebMvc。
如果希望提供 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 或 ExceptionHandler,ExceptionResolver 的自定义实例,
则可以声明 WebMVCregistrationAdapter 实例来提供此类组件。
*/
If you want to keep Spring Boot MVC features and you want to add additional MVC configuration
(interceptors, formatters, view controllers, and other features), you can add your own
class of type WebMvcConfigurer but without . If you wish to provide
custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or
ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
// 如果您想完全控制 Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc 进行注释。
If you want to take complete control of Spring MVC, you can add your own annotated with .
分析 starter-web
首先打开 Maven 的本地仓库,找到对应 Spring Boot 的文件夹,打开 spring-boot-start-web 文件夹
就可以看到一个名为 spring-boot-starter-web-2.0.7.RELEASE.pom 的文件。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starters</artifactId>
<version>2.0.7.RELEASE</version>
</parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.0.7.RELEASE</version>
<name>Spring Boot Web Starter</name>
<description>Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container</description>
<url>https://projects.spring.io/spring-boot/#/spring-boot-parent/spring-boot-starters/spring-boot-starter-web</url>
<organization>
<name>Pivotal Software, Inc.</name>
<url>https://spring.io</url>
</organization>
<licenses>
<license>
<name>Apache License, Version 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0</url>
</license>
</licenses>
<developers>
<developer>
<name>Pivotal</name>
<email>info@pivotal.io</email>
<organization>Pivotal Software, Inc.</organization>
<organizationUrl>http://www.spring.io</organizationUrl>
</developer>
</developers>
<scm>
<connection>scm:git:git://github.com/spring-projects/spring-boot.git/spring-boot-starters/spring-boot-starter-web</connection>
<developerConnection>scm:git:ssh://git@github.com/spring-projects/spring-boot.git/spring-boot-starters/spring-boot-starter-web</developerConnection>
<url>http://github.com/spring-projects/spring-boot/spring-boot-starters/spring-boot-starter-web</url>
</scm>
<issueManagement>
<system>Github</system>
<url>https://github.com/spring-projects/spring-boot/issues</url>
</issueManagement>
<dependencies>
<!-- Spring Boot 的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.0.7.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- json 的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.0.7.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- tomcat 的依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>2.0.7.RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- hibernate 的依赖-->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
<scope>compile</scope>
</dependency>
<!-- Spring Web MVC 依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.0.11.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.11.RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>通过依赖中的中文注释可以看出,当加入 spring-boot-starter-web 后,它会
通过 Maven 将 web 相关的依赖资源加载到我们的工程中,这样便能够形成依赖。但是这样还不足以运行 Spring MVC 项目,要运行它还需要对 Spring MVC 进行配置,让它能够生产 Spring MVC 所需的对象(视图解析器,过滤器等等),才能启用 Spring MVC。
MCV 自动配置
- 为了探讨 Spring MVC 在 Spring Boot 自动配置的问题,首先在本地下载的 Maven 仓库的目录 spring-boot-autoconfigure 中找到 spring-boot-autoconfigure-2.0.7.RELEASE-sources.jar 的包,它是一个源码包,把它解压缩出来。
- 打开它目录下的子目录
org\ppringframework\boot\autoconfigure\web\servlet后,我们就可以看到许多配置类,其中 DispatcherServletAutoConfiguration 就是一个对 DispatcherServlet 进行自动配置的类。
DispatcherServletAutoConfiguration
分析自动配置类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39//配置文件
//配置条件满足类 DefaultDispatcherServletCondition 的验证
//如果存在 ServletRegistration 类则进行配置
//配置属性 (Spring MVC 的是 spring.mvc.*)
protected static class DispatcherServletConfiguration {
private final WebMvcProperties webMvcProperties;
public DispatcherServletConfiguration(WebMvcProperties webMvcProperties) {
this.webMvcProperties = webMvcProperties;
}
public DispatcherServlet dispatcherServlet() {
DispatcherServlet dispatcherServlet = new DispatcherServlet();
dispatcherServlet.setDispatchOptionsRequest(
this.webMvcProperties.isDispatchOptionsRequest());
dispatcherServlet.setDispatchTraceRequest(
this.webMvcProperties.isDispatchTraceRequest());
dispatcherServlet.setThrowExceptionIfNoHandlerFound(
this.webMvcProperties.isThrowExceptionIfNoHandlerFound());
return dispatcherServlet;
}
//如果存在类定义则配置
// 判断如果不存在 bean 名称为 DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME, 则配置 Bean
public MultipartResolver multipartResolver(MultipartResolver resolver) {
// Detect if the user has created a MultipartResolver but named it incorrectly
return resolver;
}
}通过上面的代码, 可以看到 Spring Boot 内部己经自动 为我们做了很多关于 DispatcherServlet 的配置,其中的
@EnableConfigurationProperties(WebMvcProperties.class)还能够在读取配置内容的情况下自动生成 Spring MVC 所需的类,到这里应该明白为什么几乎在没有任何配置下就能用 Spring Boot 启 动 Spring MVC 项目这些都是 Spring Boot 通过 Maven 依赖找到对应的 jar 包和嵌入的服务器,然后使用默认自动配置类来创建默认的开发环境。
但是有时候,我们需要对这些默认的环境进行修改以适应个性化的要求,这些在 Spring Boot 中也是非常简单的,正如@EnableConfigurationProperties 注解那样,它允许读入配置文件的内容来自定义自动初始化所需内。
视图解析器
ContentNegotiatingViewResolver :视图解析器,该解析器会根据方法的返回值取得视图对象(View),然后由视图对象决定如何渲染(转发,重定向)。
1
2
3
4
5
6
7
8
9
10
11public interface ViewResolver {
View resolveViewName(String viewName, Locale locale) throws Exception;
}
// 实现了 ViewResolver 接口的类,我们称为视图解析器
public class ContentNegotiatingViewResolver extends WebApplicationObjectSupport
implements ViewResolver, Ordered, InitializingBean {
//....
}我们找到 jar 包下的
WebMvcAutoConfiguration, 然后搜索ContentNegotiatingViewResolver。找到如下方法!1
2
3
4
5
6
7
8
9
10
public ContentNegotiatingViewResolver viewResolver(BeanFactory beanFactory) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(beanFactory.getBean(ContentNegotiationManager.class));
// ContentNegotiatingViewResolver 使用所有其他视图解析器来定位视图,因此它应该具有较高的优先级
resolver.setOrder(Ordered.HIGHEST_PRECEDENCE);
return resolver;
}我们可以点进 ContentNegotiatingViewResolver 类看看!找到对应的解析视图的代码;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// 注解说明:@Nullable 即参数可为 null
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = this.getMediaTypes(((ServletRequestAttributes)attrs).getRequest());
if (requestedMediaTypes != null) {
// 获取候选的视图对象
List<View> candidateViews = this.getCandidateViews(viewName, locale, requestedMediaTypes);
// 选择一个最适合的视图对象,然后把这个对象返回
View bestView = this.getBestView(candidateViews, requestedMediaTypes, attrs);
if (bestView != null) {
return bestView;
}
}
// .....
}我们继续点进去看,他是怎么获得候选的视图的呢?
getCandidateViews 中看到他是把所有的视图解析器拿来,进行 for 循环,挨个解析!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32private List<View> getCandidateViews(String viewName, Locale locale, List<MediaType> requestedMediaTypes)
throws Exception {
List<View> candidateViews = new ArrayList<>();
if (this.viewResolvers != null) {
Assert.state(this.contentNegotiationManager != null, "No ContentNegotiationManager set");
//遍历所有的视图解析器
for (ViewResolver viewResolver : this.viewResolvers) {
//封装到对象
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
//添加到候选的视图
candidateViews.add(view);
}
for (MediaType requestedMediaType : requestedMediaTypes) {
List<String> extensions = this.contentNegotiationManager.resolveFileExtensions(requestedMediaType);
for (String extension : extensions) {
String viewNameWithExtension = viewName + '.' + extension;
view = viewResolver.resolveViewName(viewNameWithExtension, locale);
if (view != null) {
candidateViews.add(view);
}
}
}
}
}
if (!CollectionUtils.isEmpty(this.defaultViews)) {
candidateViews.addAll(this.defaultViews);
}
//返回候选的视图
return candidateViews;
}所以得出结论:
ContentNegotiatingViewResolver 这个视图解析器就是用来组合所有的视图解析器的,再研究下他的组合逻辑,看到有个属性 viewResolvers,看看它是在哪里进行赋值的!1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
protected void initServletContext(ServletContext servletContext) {
// 这里它是从 beanFactory 工具中获取容器中的所有视图解析器
// ViewRescolver.class 把所有的视图解析器来组合的
Collection<ViewResolver> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();
if (this.viewResolvers == null) {
this.viewResolvers = new ArrayList<>(matchingBeans.size());
for (ViewResolver viewResolver : matchingBeans) {
if (this != viewResolver) {
this.viewResolvers.add(viewResolver);
}
}
}
else {
for (int i = 0; i < this.viewResolvers.size(); i++) {
ViewResolver vr = this.viewResolvers.get(i);
if (matchingBeans.contains(vr)) {
continue;
}
String name = vr.getClass().getName() + i;
obtainApplicationContext().getAutowireCapableBeanFactory().initializeBean(vr, name);
}
}
AnnotationAwareOrderComparator.sort(this.viewResolvers);
this.cnmFactoryBean.setServletContext(servletContext);
}
自定义视图解析器
既然它是在容器中去找视图解析器,我们是否可以猜想,我们就可以去实现一个视图解析器了呢?
我们可以自己给容器中去添加一个视图解析器;这个类就会帮我们自动的将它组合进来;
我们在我们的主程序中去写一个视图解析器来试试;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32package top.fulsun.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
/**
* @className: MyViewResolver
* @Description: 实现 WebMvcConfigurer 接口
* @version: v1.8.0
* @author: Fulsun
* @date: 2020/4/5 1:58 下午
*/
//配置类
public class MyWebMvcConfig implements WebMvcConfigurer {
//放到 bean 中
public ViewResolver myViewResolver(){
return new MyViewResolver();
}
//我们写一个静态内部类,视图解析器就需要实现 ViewResolver 接口
private static class MyViewResolver implements ViewResolver{
public View resolveViewName(String s, Locale locale) throws Exception {
return null;
}
}
}看我们自己写的视图解析器有没有起作用呢?给 DispatcherServlet 中的 doDispatch 方法 加个断点进行调试一下,因为所有的请求都会走到这个方法中

我们启动我们的项目,然后随便访问一个页面,看一下 Debug 信息;
找到 this, 找到视图解析器,我们看到我们自己定义的就在这里了;

所以说,我们如果想要使用自己定制化的东西,我们只需要给容器中添加这个组件就好了!剩下的事情 SpringBoot 就会帮我们做了!
转换器和格式化器
WebMvcAutoConfiguration 中找到格式化转换器:
1
2
3
4
5
6
7
8
9
public FormattingConversionService mvcConversionService() {
// 拿到配置文件中的格式化规则
WebConversionService conversionService =
new WebConversionService(this.mvcProperties.getDateFormat());
addFormatters(conversionService);
return conversionService;
}点击进入:
1
2
3
4
5
6
7
8public String getDateFormat() {
return this.dateFormat;
}
/**
* Date format to use. For instance, `dd/MM/yyyy`. 默认的
*/
private String dateFormat;
自定义日期格式
mvcProperties 关联了配置文件,我们可以在配置文件中进行修改
在配置文件中配置日期格式化的规则:
1
2
3spring:
mvc:
date-format: dd-MM-yyyy
默认配置小结
- 这么多的自动配置,原理都是一样的。
- SpringBoot 的底层,大量用到了这些设计细节思想,所以,没事需要多阅读源码!得出结论;
- SpringBoot 在自动配置很多组件的时候,先看容器中有没有用户自己配置的(如果用户自己配置@bean),如果有就用用户配置的,如果没有就用自动配置的;
- 如果有些组件可以存在多个,比如我们的视图解析器,就将用户配置的和自己默认的组合起来!
扩展使用 SpringMVC
- 扩展:既保 SpringBoot 留所有的自动配置,也能用我们扩展的配置!
- 根据官方文档的说明,扩展 SpringMVC 只需要编写一个@Configuration 注解类并实现 WebMvcConfigurer 接口,
不能标注@EnableWebMvc注解;
自定义类扩展 MVC
新建配置类
1
2
3
4
5
6
7
8
9
10
11//应为类型要求为 WebMvcConfigurer,所以我们实现其接口
//可以使用自定义类扩展 MVC 的功能
public class MyMvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
// 浏览器发送/2 , 就会跳转到 test 页面;
registry.addViewController("/t2").setViewName("test");
}
}浏览器访问,确实也跳转过来了

扩展 MVC 的原理
WebMvcAutoConfiguration是 SpringMVC 的自动配置类,里面有一个类WebMvcAutoConfigurationAdapter这个类上有一个注解,在做其他自动配置时会导入:
@Import(EnableWebMvcConfiguration.class)我们点进
EnableWebMvcConfiguration这个类看一下,它继承了一个类:DelegatingWebMvcConfiguration这个父类中会获取容器中所有的 WebMvcConfigurer
1
2
3
4
5
6
7
8
9
10public class extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
// 从容器中获取所有的 webmvcConfigurer
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
}我们可以在这个类中去寻找 addViewControllers 当做参考,发现它调用了一个
1
2
3
4
protected void addViewControllers(ViewControllerRegistry registry) {
this.configurers.addViewControllers(registry);
}我们点进 addViewControllers 去看一下
1
2
3
4
5
6
7
public void addViewControllers(ViewControllerRegistry registry) {
for (WebMvcConfigurer delegate : this.delegates) {
// 将所有的 WebMvcConfigurer 相关配置来一起调用!包括我们自己配置的和 Spring 给我们配置的
delegate.addViewControllers(registry);
}
}所以得出结论:在运行的时候,所有的
WebMvcConfiguration相关配置都会被调用,所以通过实现 WebMvcConfiguration 接口后,就能扩展使用 SpingMVC。
全面接管 SpringMVC
官方文档:If you want to take complete control of Spring MVCyou can add your own @Configuration annotated with @EnableWebMvc.
全面接管即:SpringBoot 对 SpringMVC 的自动配置不需要了,所有都是我们自己去配置!
只需在我们的配置类中要加一个
@EnableWebMvc。我们看下如果我们全面接管了 SpringMVC 了,我们之前 SpringBoot 给我们配置的静态资源映射一定会无效,我们可以去测试一下;
不加注解之前,访问首页:

给配置类加上注解:
@EnableWebMvc
我们发现所有的 SpringMVC 自动配置都失效了!回归到了最初的样子;我们开发中,不推荐使用全面接管 SpringMVC
失效原因
为什么加了一个注解,自动配置就失效了!我们看下源码:
这里发现
@EnableWebMvc它是导入了一个类,我们可以继续进去1
2
3
public EnableWebMvc {
}它继承了一个父类
WebMvcConfigurationSupport1
2
3public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
// ......
}我们来回顾一下 Webmvc 自动配置类
1
2
3
4
5
6
7
8
9
10
11
// 这个注解的意思就是:容器中没有这个组件的时候,这个自动配置类才生效
public class WebMvcAutoConfiguration {
}总结:
@EnableWebMvc将WebMvcConfigurationSupport组件导入进来了;所以自动配置类就不生效了。
发布时间: 2020-03-27
最后更新: 2022-02-12
本文标题: SpringBoot 之配置 Spring MVC
本文链接: https://fulsun.github.io/post/bc2c.html
版权声明: 本作品采用 CC BY-NC-SA 4.0 许可协议进行许可。转载请注明出处!