SpringBoot(五)——————SpringMvc自動配置原理

參考文檔:https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/spring-boot-features.html#boot-features-developing-web-applications

  • SpringMvc自動配置原理

Spring Boot爲Spring MVC提供了自動配置,可與大多數應用程序完美配合。自動配置在Spring的默認值之上添加了以下功能:

  • 包含ContentNegotiatingViewResolverBeanNameViewResolver

自動配置了視圖解析器ViewResolver,根據方法返回值得到視圖對象(View),視圖對象決定如何渲染,轉發?重定向?

ContentNegotiatingViewResolver作用組合所有的視圖解析器

可以自己定義視圖解析器並添加到容器中,ContentNegotiatingViewResolver自動將其組合進來

 

 

  • 支持服務靜態資源,包括對WebJars的支持。靜態資源文件夾

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			Duration cachePeriod = this.resourceProperties.getCache().getPeriod();
			CacheControl cacheControl = this.resourceProperties.getCache().getCachecontrol().toHttpCacheControl();
			if (!registry.hasMappingForPattern("/webjars/**")) {
				customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
						.addResourceLocations("classpath:/META-INF/resources/webjars/")
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
			String staticPathPattern = this.mvcProperties.getStaticPathPattern();
			if (!registry.hasMappingForPattern(staticPathPattern)) {
				customizeResourceHandlerRegistration(registry.addResourceHandler(staticPathPattern)
						.addResourceLocations(getResourceLocations(this.resourceProperties.getStaticLocations()))
						.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
			}
		}
  • 自動註冊ConverterGenericConverterFormatter豆類。

    Converter:轉換器,類型轉換,頁面傳遞的參數和controller方法接收的VO對象數據類型的轉換

    Formatter:格式化器,將字符串轉成格式化的日期類型

  • 支持HttpMessageConverters

    HttpMessageConverters:SpringMvc用來轉換http請求和響應的,比如將實體對象轉換成JSON

    從容器中獲取所有的HttpMessageConverters ,也可以自定義HttpMessageConverters然後放入容器中

  • 自動註冊MessageCodesResolver

    MessageCodesResolver:定義錯誤代碼生成規則

  • 靜態index.html支持。靜態首頁訪問

  • 定製Favicon支持,自定義網頁小圖標

  • 自動使用ConfigurableWebBindingInitializerbean

    ConfigurableWebBindingInitializer:初始化WebDataBinder Web數據綁定器,請求數據與VO對象進行綁定

    SpringBoot在web下所有自動配置類在org.springframework.boot.autoconfigure.web這個路徑全部列舉

SpringMvc擴展

如果您想保留Spring Boot MVC功能,並且想要添加其他MVC配置(攔截器,格式化程序,視圖控制器和其他功能),則可以添加自己@Configuration的type類,WebMvcConfigurer不添加 @EnableWebMvc。如果您希望提供,或的自定義實例RequestMappingHandlerMapping,則可以聲明一個實例來提供此類組件。RequestMappingHandlerAdapter``ExceptionHandlerExceptionResolver``WebMvcRegistrationsAdapter

如果您想完全控制Spring MVC,可以使用添加自己的@Configuration註釋@EnableWebMvc

  • 總結:

1)、SpringMvc擴展實現WebMvcConfigurer接口添加自己要添加的方法和配置

2)、WebMvcConfigurerAdapter:SpringBoot2.0以後WebMvcConfigurerAdapter被棄用,繼承這個類自動配置都生效,自己重寫的方法也會生效。

WebMvcConfigurationSupport:如果繼承WebMvcConfigurationSupport,SpringMvc的自動配置都失效,自己重寫的方法會生效

@EnableWebMvc這個註解標記後,自動配置失效,重寫的方法失效。SpringBoot中Springmvc的一套都無效。

  • SpringBoot2.2以後就棄用了WebMvcConfigurerAdapter,需要擴展就實現WebMvcConfigurer

    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    ​
        @Override
        public void addViewControllers(ViewControllerRegistry registry) {
            registry.addViewController("/abc").setViewName("hello");
        }

     

  1. 如果標註了@EnableWebMvc這個註解那麼SpringBoot的Springmvc將全部失效。自己寫的配置全面接管SpringMvc,​​​​​​​

@ConditionalOnMissingBean(WebMvcConfigurationSupport.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 {
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {}
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
}
  • 如何修改SpringBoot的默認配置

1)、SpringBoot在自動配置很多組件的時候,先看容器中有沒有用戶自己配置的(@Bean、@Component)如果有就用用戶配置的,如果沒有,才自動配置;如果有些組件可以有多個(ViewResolver)將用戶配置的和自己默認的組合起來;

2)、在SpringBoot中會有非常多的xxxConfigurer幫助我們進行擴展配置

3)、在SpringBoot中會有很多的xxxCustomizer幫助我們進行定製配置

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章