私とspringboot(21)springboot-springmvc自動配置原理を学びます


1.springmvc構成API


公式サイトのAPIの解釈を見て、springboot公式サイトのウェブサイトを開きますhttps://docs.spring.io/spring-boot/docs/1.5.10.RELEASE/reference/htmlsingle/#boot-features-developing-web-applications spring-boot-starter-webの高速使用方法について詳しく説明しています.

2.自動配置原理


2.1auto_confifuration


Spring BootはSpringMVCを自動的に構成しました.以下はSpringBootのSpringMVCに対するデフォルト構成です.(WebMvcAutoConfiguration)
  • 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.1.Converter:コンバータ;public String hello(User):タイプ変換はConverter 2を使用する.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). デフォルトの代わりにC o n f i g u r a b eWebBindingInitializerを構成できます.(コンテナに追加)
  •    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.2 SpringMVCの拡張

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

    WebMvcConfigurerAdapterタイプの構成クラス(@Configuration)を作成します.@EnableWebMvcはマークできません.すべての自動構成が保持されているだけでなく、拡張された構成も使用できます.
    //  WebMvcConfigurerAdapter     SpringMVC   
    @Configuration
    public class MyMvcConfig extends WebMvcConfigurerAdapter {
    	@Override
    	public void addViewControllers(ViewControllerRegistry registry) {
    	// super.addViewControllers(registry);
    	//      /hello      success
    	registry.addViewController("/hello").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の自動構成と私たちの拡張構成が機能します.

    2.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");
    }
    }
    

    原理:なぜ@EnableWebMvcの自動配置が失効したのか.1)@EnableWebMvcのコア
    @Import(DelegatingWebMvcConfiguration.class)
    public @interface EnableWebMvc {
    

    2)、
    @Configuration
    public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
    

  • @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の最も基本的な機能にすぎない.

    2.5 SpringBootのデフォルト構成を変更する方法


    モード:1)、SpringBootは多くのコンポーネントを自動的に構成する際に、まずコンテナの中にユーザーが自分で構成している(@Bean、@Component)があればユーザーで構成しているかどうかを見て、なければ自動的に構成します.一部のコンポーネントが複数(ViewResolver)ある場合、ユーザー構成と自分のデフォルトを組み合わせることができます.2)、SpringBootでは多くのxxxConfigurerが拡張構成を支援してくれます3)、SpringBootでは多くのxxxCustomizerがカスタマイズ構成を支援してくれます