Springboot 2.0---WebFlux核心组件的初始化(二)

核心组件初始化流程

笔记是学习了小马哥在慕课网的课程的《Spring Boot 2.0深度实践之核心技术篇》的内容结合自己的需要和理解做的笔记。
既然说到初始化流程,那么就不能不上流程图了。

p12.png

我们通过流程图相信已经可以理解百分四五十了,那么接下来让我们来通过源码来简单的解释一下详细流程。

在之前的一篇笔记中,已经简单介绍了springboot加载配置组件流程的源码,那么现在我们就直接对照流程图的流程来对照下源码。真正的了解一下WebFlux核心组件的加载。

流程相关源码解析

我们这里就直接查看需要加载的核心组件的流程,之前的注解配置解析流程不再重复,可以看之前的笔记。

我们从流程图上的组件 一个一个看

WebFluxAutoConfiguration派生其他类

@Configuration
//条件装配 只有启动的类型是REACTIVE时加载
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
//只有存在 WebFluxConfigurer实例  时加载
@ConditionalOnClass(WebFluxConfigurer.class)
//在不存在  WebFluxConfigurationSupport实例时 加载
@ConditionalOnMissingBean({ WebFluxConfigurationSupport.class })
//在之后装配
@AutoConfigureAfter({ ReactiveWebServerFactoryAutoConfiguration.class,
      CodecsAutoConfiguration.class, ValidationAutoConfiguration.class })
//自动装配顺序
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class WebFluxAutoConfiguration {

    
   @Configuration
   @EnableConfigurationProperties({ ResourceProperties.class, WebFluxProperties.class })
   //接口编程 在装配WebFluxConfig 之前要先 装配EnableWebFluxConfiguration
   @Import({ EnableWebFluxConfiguration.class })
   public static class WebFluxConfig implements WebFluxConfigurer {
      //隐藏部分源码
        /**
     * Configuration equivalent to {@code @EnableWebFlux}.
     */
   }
    
    @Configuration
    public static class EnableWebFluxConfiguration
            extends DelegatingWebFluxConfiguration {

        //隐藏部分代码
    }
        @Configuration
    @ConditionalOnEnabledResourceChain
    static class ResourceChainCustomizerConfiguration {
        //隐藏部分代码
    }
    
    private static class ResourceChainResourceHandlerRegistrationCustomizer
            implements ResourceHandlerRegistrationCustomizer {
            //隐藏部分代码
        }
      

我们可以看到 由WebFluxAutoConfiguration 自动装配时确实由流程图中的所说 先自动装配 EnableWebFluxConfigurationEnableWebFluxConfiguration 继承了 DelegatingWebFluxConfiguration

DelegatingWebFluxConfiguration 继承了 WebFluxConfigurationSupport

@Configuration
public class DelegatingWebFluxConfiguration extends WebFluxConfigurationSupport {
...
}

所以我们来看一下 WebFluxConfigurationSupport 由于代码过长 我会把具体的实现代码省略掉

public class WebFluxConfigurationSupport implements ApplicationContextAware {
   //跨域配置
   @Nullable
   private Map<String, CorsConfiguration> corsConfigurations;
   //路径HandlerMapping 对应的路径配置
   @Nullable
   private PathMatchConfigurer pathMatchConfigurer;
   //视图解析器
   @Nullable
   private ViewResolverRegistry viewResolverRegistry;
   //上下文
   @Nullable
   private ApplicationContext applicationContext;

   //声明DispatcherHandler 对象 注入到容器中
   @Bean
   public DispatcherHandler webHandler() {
      return new DispatcherHandler();
   }
   
   //异常处理器 
   @Bean
   @Order(0)
   public WebExceptionHandler responseStatusExceptionHandler() {
      return new WebFluxResponseStatusExceptionHandler();
   }

   //requestMappingHandlerMapping 和SrpingMvc组件一样
   @Bean
   public RequestMappingHandlerMapping requestMappingHandlerMapping() {
      RequestMappingHandlerMapping mapping = createRequestMappingHandlerMapping();
      mapping.setOrder(0);    //这里把映射顺序设置为 0 
      mapping.setContentTypeResolver(webFluxContentTypeResolver());
      mapping.setCorsConfigurations(getCorsConfigurations());    
      //省略部分代码
      return mapping;
   }
   //省略部分代码
   
   //Webflux内容协商处理器
   @Bean
   public RequestedContentTypeResolver webFluxContentTypeResolver() {
      RequestedContentTypeResolverBuilder builder = new RequestedContentTypeResolverBuilder();
      configureContentTypeResolver(builder);
      return builder.build();
   }
   //省略部分代码
  //WebFlux 的请求映射处理器 在 RequestMappingHandlerMapping 之前
   @Bean
   public RouterFunctionMapping routerFunctionMapping() {
      RouterFunctionMapping mapping = createRouterFunctionMapping();
      mapping.setOrder(-1); // go before RequestMappingHandlerMapping
      mapping.setMessageReaders(serverCodecConfigurer().getReaders());
      mapping.setCorsConfigurations(getCorsConfigurations());
      return mapping;
   }

  //省略部分代码
    //其他映射处理器 这里默认是 SimpleUrlHandlerMapping 
   @Bean
   public HandlerMapping resourceHandlerMapping() {
      ResourceLoader resourceLoader = this.applicationContext;
      if (resourceLoader == null) {
         resourceLoader = new DefaultResourceLoader();
      }
      ResourceHandlerRegistry registry = new ResourceHandlerRegistry(resourceLoader);
      addResourceHandlers(registry);
      AbstractHandlerMapping handlerMapping = registry.getHandlerMapping();
      if (handlerMapping != null) {
         PathMatchConfigurer configurer = getPathMatchConfigurer();
         Boolean useTrailingSlashMatch = configurer.isUseTrailingSlashMatch();
         Boolean useCaseSensitiveMatch = configurer.isUseCaseSensitiveMatch();
         if (useTrailingSlashMatch != null) {
            handlerMapping.setUseTrailingSlashMatch(useTrailingSlashMatch);
         }
         if (useCaseSensitiveMatch != null) {
            handlerMapping.setUseCaseSensitiveMatch(useCaseSensitiveMatch);
         }
      }
      else {
         handlerMapping = new EmptyHandlerMapping();
      }
      return handlerMapping;
   }
   //请求适配器 支持 WebFlux
   @Bean
   public RequestMappingHandlerAdapter requestMappingHandlerAdapter() {
      RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
      adapter.setMessageReaders(serverCodecConfigurer().getReaders());
      adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer());
      adapter.setReactiveAdapterRegistry(webFluxAdapterRegistry());
      ArgumentResolverConfigurer configurer = new ArgumentResolverConfigurer();
      configureArgumentResolvers(configurer);
      adapter.setArgumentResolverConfigurer(configurer);

      return adapter;
   }
   //省略部分代码
   //国际化解析器
   @Bean
   public LocaleContextResolver localeContextResolver() {
      return createLocaleContextResolver();
   }

   //省略部分代码

   //WebFlux路由形式的适配器
   @Bean
   public HandlerFunctionAdapter handlerFunctionAdapter() {
      return new HandlerFunctionAdapter();
   }
   //省略部分代码

}

我们可以看到 WebFluxConfigurationSupport 不仅配置DispatcherHandler 还同时配置了其他很多WebFlux核心组件包括异常处理,内容协商处理器等。

ApplicationContext依赖查找 WebHandler等操作

组件都有了 那么我们时何时注入到上容器下文中的呢? 在这里 其实是在 刷新上下文时注入的,核心代码如下

org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext#onRefresh

@Override
protected void onRefresh() {
   super.onRefresh();
   try {
       //创建Reactive Web Server
      createWebServer();
   }
   catch (Throwable ex) {
      throw new ApplicationContextException("Unable to start reactive web server",
            ex);
   }
}

我们可以看到在刷新上下文的时候,我们调用了 createWebServer() 方法来创建 Reactive Web Server。

private void createWebServer() {
   WebServer localServer = this.webServer;
   if (localServer == null) {
      this.webServer = getWebServerFactory().getWebServer(getHttpHandler());
   }
   initPropertySources();
}

在这段代码就是把之前的 DispatcherHandler 与上下文联系了起来,而通过getHttpHandler() 调用将 HttpHandlerAutoConfiguration实例化。

@Configuration
@ConditionalOnClass({ DispatcherHandler.class, HttpHandler.class })
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnMissingBean(HttpHandler.class)
@AutoConfigureAfter({ WebFluxAutoConfiguration.class })
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
public class HttpHandlerAutoConfiguration {

   @Configuration
   public static class AnnotationConfig {

      private ApplicationContext applicationContext;

      public AnnotationConfig(ApplicationContext applicationContext) {
         this.applicationContext = applicationContext;
      }

      //构建WebHandler
      @Bean
      public HttpHandler httpHandler() {
         return WebHttpHandlerBuilder.applicationContext(this.applicationContext)
               .build();
      }

   }

}

直接通过 org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration.AnnotationConfig#httpHandler 构建WebHadler 。构建的内容就如开头的流程图一样 ,下面配上源码 ,相信大家一看就懂了。

/**
 * Build the {@link HttpHandler}.
 */
public HttpHandler build() {
    //声明 FilteringWebHandler
   WebHandler decorated = new FilteringWebHandler(this.webHandler, this.filters);
    //包装 ExceptionHandlingWebHandler
   decorated = new ExceptionHandlingWebHandler(decorated,  this.exceptionHandlers);

    //继续包装
   HttpWebHandlerAdapter adapted = new HttpWebHandlerAdapter(decorated);
   
    //配置注入
   if (this.sessionManager != null) {
      adapted.setSessionManager(this.sessionManager);
   }
   if (this.codecConfigurer != null) {
      adapted.setCodecConfigurer(this.codecConfigurer);
   }
   if (this.localeContextResolver != null) {
      adapted.setLocaleContextResolver(this.localeContextResolver);
   }
   if (this.applicationContext != null) {
      adapted.setApplicationContext(this.applicationContext);
   }

   return adapted;
}

主要的装配流程已经简单的介绍完毕。

总结

IT行业技术更新是在太快,以上的内容都是为了方便以后自己回头看的时候可以很快的回忆起当时学习的内容,说实话,从这段debugger源码的过程中,收获很多,让我更进一步了解了SpringBoot的自动装配。虽然现在的理解可能是冰山一角,但是随着我们慢慢的深入或者大牛的分享,相信会更深一步的理解博大精深的Spring。

Demo地址

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容