[SpringBoot系列】前文:
SpringBoot-web開發(一): 靜態資源的匯入(原始碼分析)
SpringBoot-web開發(二): 頁面和圖示定制(原始碼分析)
SpringBoot-web開發(三): 模板引擎Thymeleaf
目錄
- 一. 解讀官方檔案
- 二. 拓展SpringMVC
- 1. 拓展原理
- 2. 環境搭建:撰寫拓展配置類
- 3. 示例:拓展視圖決議器
- 1. 默認視圖決議器原始碼分析
- 2. 自定義視圖決議器
- 4. 修改SpringBoot默認配置
- 示例:修改默認日期格式
- 5. 總結
- 三. 全面接管SpringMVC
- 1. 什么是全面接管?
- 2. 測驗
- 3. @EnableWebMvc原理
一. 解讀官方檔案
SpringBoot在底層對我們的SpringMVC新增了很多配置,我們接下來需要了解如何擴展,如何定制自己的配置
官方檔案點擊這里:官方檔案

Spring Boot為Spring MVC提供了自動配置,可與大多數應用程式完美配合
自動配置在Spring的默認設定之上添加了以下功能:
- 包含
ContentNegotiatingViewResolver和BeanNameViewResolverbeans(視圖決議器) - 支持服務靜態資源,包括對WebJars的支持
- 自動注冊
Converter,GenericConverter(型別轉換器)和Formatter(格式化器)beans - 對
HttpMessageConverters(訊息轉換,轉換Http請求和回應)的支持 - 自動注冊
MessageCodesResolver(生成系結錯誤訊息) - 靜態
index.html支持(首頁映射) - 自定義
Favicon支持(圖示自定義) - 自動使用
ConfigurableWebBindingInitializerbean(資料web的初始化系結)
使用方法:
如果要保留這些SpringBoot MVC特點并添加更多的MVC功能(攔截器,格式化程式,視圖控制器和其他功能),則將@Configuration注解添加到型別為WebMvcConfigurer的類上,但不添加@EnableWebMvc注解
如果要提供RequestMappingHandlerMapping,RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定義實體,并且仍然保留Spring Boot MVC自定義,則可以宣告WebMvcRegistrations型別的bean,并使用它提供這些組件的自定義實體
如果要完全控制Spring MVC,則可以添加用@EnableWebMvc注解的自己的@Configuration,或者按照@EnableWebMvc的Javadoc中的說明添加自己的@Configuration注解的DelegatingWebMvcConfiguration
二. 拓展SpringMVC
根據官方檔案:如果要保留這些SpringBoot MVC特點并添加更多的MVC功能(攔截器,格式化程式,視圖控制器和其他功能),則將
@Configuration注解添加到型別為WebMvcConfigurer的類上,但不添加@EnableWebMvc注解
1. 拓展原理
我們查看SpringBoot底層webmvc自動配置類WebMvcAutoConfiguration中的自動適配類WebMvcAutoConfigurationAdapter

可以看到這樣一個注解@Import(EnableWebMvcConfiguration.class)
也就是匯入了EnableWebMvcConfiguration這個類
我們繼續查看該類原始碼,發現它繼承了一個父類DelegatingWebMvcConfiguration
我們繼續查看DelegatingWebMvcConfiguration的原始碼,可以找到這樣一個方法

@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}
該方法就是從Spring容器中獲取所有的webmvcConfigurer,及所有的配置類
也就是SpringBoot在底層自動獲取了所有的配置類,包括默認的配置類以及我們自定義的配置類,這也就是我們拓展的原理,我們可以新增自己配置類,注入到Spring容器中,然后SpringBoot即可自動配置
2. 環境搭建:撰寫拓展配置類
接下來,我們搭建一個拓展配置類環境進行實驗:
首先在主程式同級目錄下新建一個
congfig包,用來放置的配置類,其中新建配置類MyMvcConfiguration用來拓展裝配MVC的配置![]()
通過官方檔案的介紹,我們需要將@Configuration注解添加到型別為WebMvcConfigurer的類上,但不添加@EnableWebMvc注解
因此我們現在IDEA中搜索(連按shift)一下WebMvcConfigurer,可以發現它是一個介面

因此我們需要自定義的配置類MyMvcConfiguration需要實作這個介面
package com.zsr.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
}
3. 示例:拓展視圖決議器
搭建好配置類環境后,我們接下來以官方檔案中的第一條視圖決議器為例,配置拓展一個自定義的視圖決議器
在SpringMVC中,我們在其組態檔中手動配置
視圖決議器;<!--視圖決議器:DispatcherServlet給他的ModelAndView 1.獲取了ModelAndView的資料 2.決議ModelAndView的視圖名字 3.拼接視圖名字,找到對應的視圖 hello 4.將資料渲染到這個視圖上 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--前綴--> <property name="prefix" value="/WEB-INF/jsp/"/> <!--后綴--> <property name="suffix" value=".jsp"/> </bean>而在SpringBoot,自動配置了視圖決議器;我們接下來查看原始碼,分析一下其配置好的的視圖決議器;
1. 默認視圖決議器原始碼分析
官網檔案中提到SpringBoot默認的一個視圖決議器
ContentNegotiatingViewResolver,我們來分析分析
我們在IDEA中搜索ContentNegotiatingViewResolver類

發現它實作了ViewResolver介面,我們繼續查看ViewResolver的原始碼

其中有一個決議視圖名稱方法resolveViewName
我們查看ContentNegotiatingViewResolver繼承ViewResolver介面實作的該方法
public View resolveViewName(String viewName, Locale locale) throws Exception {
RequestAttributes attrs = RequestContextHolder.getRequestAttributes();
Assert.state(attrs instanceof ServletRequestAttributes, "No current ServletRequestAttributes");
List<MediaType> requestedMediaTypes = getMediaTypes(((ServletRequestAttributes) attrs).getRequest());
if (requestedMediaTypes != null) {
// 獲取候選的視圖物件
List<View> candidateViews = getCandidateViews(viewName, locale, requestedMediaTypes);
// 選擇一個最適合的視圖對象,然后把這個物件回傳
View bestView = getBestView(candidateViews, requestedMediaTypes, attrs);
if (bestView != null) {
return bestView;
}
}
String mediaTypeInfo = logger.isDebugEnabled() && requestedMediaTypes != null ?
" given " + requestedMediaTypes.toString() : "";
if (this.useNotAcceptableStatusCode) {
if (logger.isDebugEnabled()) {
logger.debug("Using 406 NOT_ACCEPTABLE" + mediaTypeInfo);
}
return NOT_ACCEPTABLE_VIEW;
}
else {
logger.debug("View remains unresolved" + mediaTypeInfo);
return null;
}
}
可以發現該方法,就是從候選的視圖中篩選出最好的視圖,我們點開getCandidateViews方法看看如何獲取候選的視圖
private 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;
}
那么所有的視圖是從那里來的呢?我們可以找到initServletContext方法,該方法就是得到所有視圖決議器的方法
@Override
protected void initServletContext(ServletContext servletContext) {
//從BeanFactoryUtils工具類中獲取容器中的所有視圖決議器
Collection<ViewResolver> matchingBeans =
BeanFactoryUtils.beansOfTypeIncludingAncestors(obtainApplicationContext(), ViewResolver.class).values();//ViewRescolver.class 把所有的視圖決議器來組合的
if (this.viewResolvers == null) {
this.viewResolvers = new ArrayList<>(matchingBeans.size());
for (ViewResolver viewResolver : matchingBeans) {
if (this != viewResolver) {
this.viewResolvers.add(viewResolver);
}
}
}
//...
}
其中從BeanFactoryUtils工具類中獲取容器中的所有視圖決議器,然后再對其進行賦值,拿來組合
因此:SpringBoot默認的ContentNegotiatingViewResolver視圖決議器就是用來組合所有的視圖決議器的
2. 自定義視圖決議器
上述默認的
ContentNegotiatingViewResolver類通過在Spring容器中去找視圖決議器并進行組合那如果我們自己向Spring容器中去添加一個視圖決議器,這個類也會幫我們自動的將它組合進來
這樣是不是就實作了拓展一個自定義的視圖決議器呢?我們可以試試!
在上述撰寫好的配置類MyMvcConfig類中撰寫一個自己的視圖決議器靜態內部類,實作視圖決議器ViewResolver介面,重寫其抽象方法
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
//將自定義視圖決議器實作類物件注入到bean中
@Bean
public ViewResolver myViewResolver() {
return new MyViewResolver();
}
//自定義視圖決議器實作類
static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
接下來我們通過打斷點查看我們自定義的視圖決議器是否生效
我們給DispatcherServlet類中的doDispatch方法加個斷點進行除錯一下,因為所有的請求都會走到這個方法中

然后我們Debug主程式

程式啟動后,訪問localhost:8080,程式進入doDispatcher方法
我們點擊this可以查看所有的視圖決議器物件

`ContentNegotiatingViewResolver`:SpringBoot默認視圖決議器
`BeanNameViewResolver`:SpringBoot默認視圖決議器
`TymeleafViewResolver`:匯入了Tymeleaf模板引擎后Tymeleaf的視圖決議器
`MyViewResolver`:我們自定義的視圖決議器
我們發現了自定義的視圖決議器,證明ContentNegotiatingViewResolver成功將我們自定義的視圖決議器組合進來;
4. 修改SpringBoot默認配置
上述我們通過拓展視圖決議器的例子簡單了解了如何在SpringBoot新增自定義功能
我們還可以直接通過修改默認的配置達到自己想要的效果,接下來我們以修改默認的日期格式為例,找尋修改默認配置的方法
示例:修改默認日期格式
SpringBoot底層的自動裝配,都在
WebMvcAutoConfiguration自動配置類中,可以在其中找到關于格式化的方法mvcConversionService()
找到格式化轉換器:
@Bean
@Override
public FormattingConversionService mvcConversionService() {
//獲取組態檔中的格式化規則
Format format = this.mvcProperties.getFormat();
WebConversionService conversionService = new WebConversionService(new DateTimeFormatters()
.dateFormat(format.getDate()).timeFormat(format.getTime()).dateTimeFormat(format.getDateTime()));
addFormatters(conversionService);
return conversionService;
}
可以發現是從組態檔中獲取格式化的規則,然后我們按住ctrl點擊mvcProperties
private final WebMvcProperties mvcProperties;
然后點擊進入WebMvcPropertieswebMVC的組態檔類,可以找到關于日期格式化的方法
可以看到我們可以通過spring.mvc.format.date在組態檔中設定自定義日期格式,但是已經不推薦使用了
@Deprecated
@DeprecatedConfigurationProperty(replacement = "spring.mvc.format.date")
public String getDateFormat() {
return this.format.getDate();
}
我們再點擊getDate方法
public String getDate() {
return this.date;
}
再點擊date
public static class Format {
/**
* Date format to use, for example `dd/MM/yyyy`.
*/
private String date;
...
}
可以看到默認的日期格式為dd/MM/yyyy
我們可以在組態檔中修改默認的格式,自定義日期格式,比如這里為dd-MM-yyyy
spring.mvc.format.date=dd-MM-yyyy
如果配置了自己的格式化方式,就會注冊到Bean中生效,以后就必須按照自定義的日期格式書寫
其余的默認配置亦是如此,我們都可以在原始碼中找到答案
5. 總結
通過上述拓展原理以及示例,我們可以得出以下結論:
- SpringBoot的底層,大量用到了上述設計細節思想,很多的自動配置,原理都相同;
- 如果我們想自定義一些功能組件,只需要給Spring容器中添加這個組件,然后SpringBoot就會幫我們自動配置了
- SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(如果用戶自己配置@bean),如果有就用用戶配置的,如果沒有就用自動配置的;
- 如果有些組件可以存在多個,比如我們的視圖決議器,就將用戶配置的和自己默認的組合起來!
三. 全面接管SpringMVC
1. 什么是全面接管?
全面接管:SpringBoot對SpringMVC的自動配置不再需要,所有東西都是我們自己去配置!
- 實際開發中,并不推薦使用全面接管SpringMVC
- 而是推薦拓展配置,使用SpringBoot的自動配置和我們自己寫的擴展配置相結合的方式進行開發
在官方檔案中可以看到:如果要完全控制Spring MVC
-
可以添加用
@EnableWebMvc注解的自己的@Configuration -
或者按照
@EnableWebMvc的Javadoc中的說明添加自己的@Configuration注解的DelegatingWebMvcConfiguration
2. 測驗
根據官方檔案,我們在配置類上添加@EnableWebMvc注解即實作全面接管SpringMVC
package com.zsr.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 org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.Locale;
@Configuration
@EnableWebMvc
public class MyMvcConfig implements WebMvcConfigurer {
//將自定義視圖決議器實作類物件注入到bean中
@Bean
public ViewResolver myViewResolver() {
return new MyViewResolver();
}
//自定義視圖決議器實作類
static class MyViewResolver implements ViewResolver {
@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
return null;
}
}
}
我們重啟主程式進行測驗,訪問localhost:8080

可以看到先前配置的主頁已經失效,所有都回歸到了最初的樣子
3. @EnableWebMvc原理
為什么加了這個注解,自動配置就失效了,我們來一探究竟~
我們查看@EnableWebMvc注解原始碼,發現匯入了類DelegatingWebMvcConfiguration類
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
進入該類看看,發現它繼承了一個父類WebMvcConfigurationSupport
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
//...
}
也就是說,我們使用了@EnableWebMvc注解,就相當于匯入了WebMvcConfigurationSupport類
我們再查看Webmvc自動配置類WebMvcAutoConfiguration

可以這樣一個注解@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
意思是:在WebMvcConfigurationSupport類不存在的情況下生效
也就是如果這個類存在,則整個WebMvcAutoConfiguration自動配置類會失效,即SpringBoot的自動配置全部失效
而我們匯入@EnableWebMvc注解,就匯入了WebMvcConfigurationSupport類,因此SpringBoot所有的自動配置失效
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/143795.html
標籤:其他
