Springboot MVC 自動配置
官方檔案閱讀
https://docs.spring.io/spring-boot/docs/current/reference/html/web.html#web.servlet.spring-mvc.auto-configuration
Spring Boot provides auto-configuration for Spring MVC that works well with most applications.
The auto-configuration adds the following features on top of Spring’s defaults:
- Inclusion of
ContentNegotiatingViewResolverandBeanNameViewResolverbeans. - Support for serving static resources, including support for WebJars (covered later in this document).
- Automatic registration of
Converter,GenericConverter, andFormatterbeans. - Support for
HttpMessageConverters(covered later in this document). - Automatic registration of
MessageCodesResolver(covered later in this document). - Static
index.htmlsupport. - Automatic use of a
ConfigurableWebBindingInitializerbean (covered later in this document).
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
如果您希望保留 Spring Boot MVC 定制并進行更多的 MVC 定制(攔截器、格式化程式、視圖控制器和其他特性) ,可以添加您自己的 webmvcrer 型別的@Configuration 類,但不要添加@EnableWebMvc,
If you want to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, and still keep the Spring Boot MVC customizations, you can declare a bean of type WebMvcRegistrations and use it to provide custom instances of those components.
如果你想提供自定義的 requestmappinghandler mapping、 requestmappinghandler adapter 或 exceptionhandlerexceptionmvc 定制,你可以宣告一個型別為 WebMvcRegistrations 的 bean,并使用它來提供這些組件的自定義實體
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
如果你想完全控制 Spring MVC,你可以添加你自己的@Configuration 注釋@EnableWebMvc,或者像在@EnableWebMvc 的 Javadoc 中描述的那樣添加你自己的@Configuration 注釋 delegatingwebmvcvc 配置,
個人解讀
? SpringBoot本身是為Spring MVC提供了自動配置,一般情況下是滿足使用需求的,最近在學習的時候,需要使用矩陣變數,需要對springmvc的配置需要進行更改,遇到了一些疑問,通過原始碼探索了一下,今天在此總結,方便以后自己來看,
? 上面的官方檔案中,最重要的兩段話:
If you want to keep those Spring Boot MVC customizations and make more MVC customizations (interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.(在自動配置的基礎上,進行用戶自定義配置)
如果您希望保留 Spring Boot MVC 定制并進行更多的 MVC 定制(攔截器、格式化程式、視圖控制器和其他特性) ,可以添加您自己的 WebMvcConfigurer型別的@Configuration 類,但不要添加@EnableWebMvc,
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc, or alternatively add your own @Configuration-annotated DelegatingWebMvcConfiguration as described in the Javadoc of @EnableWebMvc.
如果你想完全控制 Spring MVC,你可以添加你自己的@Configuration 注釋@EnableWebMvc,或者添加自己的
@Configuration-annotatedDelegatingWebMvcConfiguration中的Javadoc中所述@EnableWebMvc,
總結一下:如果我們需要定制適合當前開發需求的springmvc,那么有兩種方法:
- (推薦)在使用@Configuration注解的配置類中,實作WebMvcConfigurer介面并重寫對應方法或者添加一個用戶自定義的WebMvcConfigurer組件,但不能使用@EnableWebMvc
- 使用@Configuration注解的同時,使用@EnableWebMvc
深入理解
首先我們得知道:(推薦使用在自動配置的基礎上進行更多定制,即同時使用自動配置以及用戶自定義配置)
? SpringBoot會默認自動配置組件,在自動配置組件的時候,首先會查看IOC容器中是否有用戶自定義配置的(即,在@Configuration配置類中,用戶使用@Bean添加進容器中的組件),如果有就用用戶配置的,如果沒有就用自動配置的;如果有些組件可以存在多個,比如我們的視圖決議器,就將用戶配置的和自己默認的組合起來,
示例代碼
? 這里是推薦方法的使用,至于全面接管的使用,后面再更新吧(如果你看到了這句話,那還沒有更新.........)
- 第一種,實作WebMvcConfigurer介面并重寫對應方法
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
// 移除url中分號:設定為false,不移除;這樣,才能從url中取出矩陣變數的值
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
- 第二種:在配置類中,用戶使用WebMvcConfigurer定制化SpringMVC的功能,并添加到容器中
@Configuration
public class WebConfig /*implements WebMvcConfigurer*/ {
// WebMvcConfigurer定制化SpringMVC的功能
@Bean
public WebMvcConfigurer webMvcConfigurer(){
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
UrlPathHelper urlPathHelper = new UrlPathHelper();
// 不移除;后面的內容,矩陣變數功能就可以生效
urlPathHelper.setRemoveSemicolonContent(false);
configurer.setUrlPathHelper(urlPathHelper);
}
}
自動配置原理(推薦方法)
WebMvcConfigurer
-
我們知道springboot是自動配置類是WebMvcAutoConfiguration.class:
@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 { ...... } -
WebMvcAutoConfiguration.class中有一個靜態類WebMvcAutoConfigurationAdapter,實作了WebMvcConfigurer:
@Configuration(proxyBeanMethods = false) @Import(EnableWebMvcConfiguration.class) @EnableConfigurationProperties({ WebMvcProperties.class, WebProperties.class }) @Order(0) public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer, ServletContextAware {...} -
WebMvcAutoConfigurationAdapter類是實作了WebMvcConfigurer介面,WebMvcConfigurer中提供了許多默認實作的方法,我們正是通過對這些方法的重寫,來達到定制的目的,
public interface WebMvcConfigurer { default void configurePathMatch(PathMatchConfigurer configurer) { } ....... } -
從注解@Import(EnableWebMvcConfiguration.class)看到,WebMvcAutoConfiguration匯入了一個配置等效于@EnableWebMvc的配置類,這個類繼承了DelegatingWebMvcConfiguration,而DelegatingWebMvcConfiguration繼承了WebMvcConfigurationSupport,
DelegatingWebMvcConfiguration這個類的作用:其實是呼叫WebMvcConfigurerComposite這個類中的方法,目的是同時加載自動配置和用戶自定義的配置
/** * A subclass of {@code WebMvcConfigurationSupport} that detects and delegates * to all beans of type {@link WebMvcConfigurer} allowing them to customize the * configuration provided by {@code WebMvcConfigurationSupport}. This is the * class actually imported by {@link EnableWebMvc @EnableWebMvc}. * * @author Rossen Stoyanchev * @since 3.1 *WebMvcConfigurationSupport的子類,它檢測并委托給WebMvcConfigurer型別的所有bean,允許它們自定義WebMvcConfigurationSupport提供的配置, 這是由@EnableWebMvc實際匯入的@EnableWebMvc */ @Configuration(proxyBeanMethods = false) public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport { private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite(); @Autowired(required = false) public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.configurers.addWebMvcConfigurers(configurers); } } ........ }我們隨機選擇這個類中任意一個方法,并進入到呼叫的對應WebMvcConfigurerComposite類中的方法,可以發現:
這個類的方法,將實作所有WebMvcConfigurer的相關配置bean,包括我們自己配置的和SpringBoot給我們自動配置的,即這里完成了在自動配置的基礎上增加我們自定義的配置,下面給出兩個示例方法:
@Autowired(required = false) public void setConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { // 從容器中獲取所有自定義配置bean this.configurers.addWebMvcConfigurers(configurers); } } @Override protected void configurePathMatch(PathMatchConfigurer configurer) { // 遍歷容器中中相關配置并呼叫 this.configurers.configurePathMatch(configurer); }查看configurePathMatch()方法:
將各種自定義配置bean(即WebMvcConfigurer物件)添加到delegates中,并將所有的WebMvcConfigurer相關配置使用對應的方法進行遍歷呼叫(包括springboot自動配置的和我們用戶自定義配置的),
class WebMvcConfigurerComposite implements WebMvcConfigurer { private final List<WebMvcConfigurer> delegates = new ArrayList<>(); public void addWebMvcConfigurers(List<WebMvcConfigurer> configurers) { if (!CollectionUtils.isEmpty(configurers)) { this.delegates.addAll(configurers); } } @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 遍歷呼叫實作,實作默認的配置以及自定義的配置 for (WebMvcConfigurer delegate : this.delegates) { delegate.configurePathMatch(configurer); } } .... }
總結1
所有的WebMvcConfiguration都會被呼叫,包括springboot自動配置的內容以及我們自己定義的配置,
為什么不能使用@EnableWebMvc(完全控制Spring MVC)
? 完全控制Spring MVC:SpringBoot對SpringMVC的自動配置失效,所有配置都需要用戶自己去配置,
前面提到,如果使用第一種方法的話,就不能使用@EnableWebMvc注解,從WebMvcConfigurer的實作類WebMvcAutoConfigurationAdapter所在的springboot自動配置類WebMvcAutoConfiguration可以看到:
@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這個組件時,才能使用SpringBoot的自動配置,所以,當我們使用第一種自動配置+自定義配置時,不能使用@EnableWebMvc注解的原因就在此,(從自動配置類WebMvcAutoConfiguration直觀分析)
進一步理解,加入@EnableWebMvc注解后SpringMVC的所有自動配置失效的原理:
- 查看@EnableWebMvc注解的定義:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
- 這個要匯入DelegatingWebMvcConfiguration組件:
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {...}
可以看到DelegatingWebMvcConfiguration是繼承WebMvcConfigurationSupport,也就是說如果使用注解@EnableWebMvc,就會向容器添加組件DelegatingWebMvcConfiguration,等同于匯入了WebMvcConfigurationSupport,這與springboot自動配置類使用的條件沖突,導致自動配置失效,
總結2
@EnableWebMvc將WebMvcConfigurationSupport組件匯入進容器中來了,會導致自動配置失效,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/388906.html
標籤:Java
