6、SpringBoot之SpringMVC自動配置

1. Spring MVC auto-configuration

項目地址:https://github.com/Chakid/SpringBoot-example

Spring Boot 自動配置好了SpringMVC

以下是SpringBoot對SpringMVC的默認配置:(WebMvcConfigurationSupport)

  • Inclusion of ContentNegotiatingViewResolver and BeanNameViewResolver beans.

    • 自動配置了ViewResolver(視圖解析器:根據方法的返回值得到視圖對象(View),視圖對象決定如何渲染(轉發?重定向?))
    • ContentNegotiatingViewResolver:組合所有的視圖解析器的;
    • 如何定製:我們可以自己給容器中添加一個視圖解析器;自動的將其組合進來;
  • Support for serving static resources, including support for WebJars (see below).靜態資源文件夾路徑,webjars

  • Static index.html support. 靜態首頁訪問

  • Custom Favicon support (see below). favicon.ico

  • 自動註冊了 of Converter, GenericConverter, Formatter beans.

    • Converter:轉換器; public String hello(User user):類型轉換使用Converter
    • Formatter 格式化器; 2017.12.17===Date;
		@Bean
		@ConditionalOnProperty(prefix = "spring.mvc", name = "date-format")//在文件中配置日期格式化的規則
		public Formatter<Date> dateFormatter() {
			return new DateFormatter(this.mvcProperties.getDateFormat());//日期格式化組件
		}

自己添加的格式化器轉換器,我們只需要放在容器中即可

  • Support for HttpMessageConverters (see below).

    • HttpMessageConverter:SpringMVC用來轉換Http請求和響應的;User—Json;

    • HttpMessageConverters 是從容器中確定;獲取所有的HttpMessageConverter;

      自己給容器中添加HttpMessageConverter,只需要將自己的組件註冊容器中(@Bean,@Component)

  • Automatic registration of MessageCodesResolver (see below).定義錯誤代碼生成規則

  • Automatic use of a ConfigurableWebBindingInitializer bean (see below).

    我們可以配置一個ConfigurableWebBindingInitializer來替換默認的;(添加到容器)

    初始化WebDataBinder;
    請求數據=====JavaBean;
    

org.springframework.boot.autoconfigure.web:web的所有自動場景;

If you want to keep Spring Boot MVC features, and you just want to add additional MVC configuration (interceptors, formatters, view controllers etc.) you can add your own @Configuration class of type WebMvcConfigurerAdapter, but without @EnableWebMvc. If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter or ExceptionHandlerExceptionResolver you can declare a WebMvcRegistrationsAdapter instance providing such components.

If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

2、擴展SpringMVC

    <mvc:view-controller path="/hello" view-name="success"/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/hello"/>
            <bean></bean>
        </mvc:interceptor>
    </mvc:interceptors>

編寫一個配置類(@Configuration),是WebMvcConfigurationSupport類型;不能標註@EnableWebMvc;

既保留了所有的自動配置,也能用我們擴展的配置;

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@Configuration
public class MyMvcConfig extends WebMvcConfigurationSupport{

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發送 /atguigu 請求來到 success
        registry.addViewController("/chakid").setViewName("success");
    }
}

原理:

​ 1)、WebMvcAutoConfiguration是SpringMVC的自動配置類

​ 2)、在做其他自動配置時會導入;@Import(EnableWebMvcConfiguration.class)

    @Configuration
	public static class EnableWebMvcConfiguration extends DelegatingWebMvcConfiguration {
      private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();

	 //從容器中獲取所有的WebMvcConfigurer
      @Autowired(required = false)
      public void setConfigurers(List<WebMvcConfigurer> configurers) {
          if (!CollectionUtils.isEmpty(configurers)) {
              this.configurers.addWebMvcConfigurers(configurers);
            	//一個參考實現;將所有的WebMvcConfigurer相關配置都來一起調用;  
            	@Override
             // public void addViewControllers(ViewControllerRegistry registry) {
              //    for (WebMvcConfigurer delegate : this.delegates) {
               //       delegate.addViewControllers(registry);
               //   }
              }
          }
	}

​ 3)、容器中所有的WebMvcConfigurer都會一起起作用;

​ 4)、我們的配置類也會被調用;

​ 效果:SpringMVC的自動配置和我們的擴展配置都會起作用;

3、全面接管SpringMVC;

SpringBoot對SpringMVC的自動配置不需要了,所有都是我們自己配置;所有的SpringMVC的自動配置都失效了

我們需要在配置類中添加@EnableWebMvc即可;

//使用WebMvcConfigurerAdapter可以來擴展SpringMVC的功能
@EnableWebMvc
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
       // super.addViewControllers(registry);
        //瀏覽器發送 /atguigu 請求來到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
}

啓動程序,訪問 http://127.0.0.1:8080/chakid
image.png

原理:

爲什麼@EnableWebMvc自動配置就失效了;

1)@EnableWebMvc的核心

@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {

2)、

@Configuration
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {

3)、

@Configuration
@ConditionalOnWebApplication
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class,
		WebMvcConfigurerAdapter.class })
//容器中沒有這個組件的時候,這個自動配置類才生效
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
@AutoConfigureAfter({ DispatcherServletAutoConfiguration.class,
		ValidationAutoConfiguration.class })
public class WebMvcAutoConfiguration {

4)、@EnableWebMvc將WebMvcConfigurationSupport組件導入進來;

5)、導入的WebMvcConfigurationSupport只是SpringMVC最基本的功能;

5、如何修改SpringBoot的默認配置

模式:

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

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

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

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