SpringBoot定制Sevlet容器原理

 我们定制的Servlet容器或SpringBoot定制的Servlet容器是怎样在SpringBoot应用生效的

首先在ServletWebServerFactoryAutoConfiguration类里
@Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,//给容器中导入了BeanPostProcessorsRegistrar组件
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
      BeanDefinitionRegistry registry) {
   if (this.beanFactory == null) {
      return;
   }
   registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor",
         WebServerFactoryCustomizerBeanPostProcessor.class);//导入了WebServerFactoryCustomizerBeanPostProcessor

//Servlet容器工厂初始化前进行的配置操作
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
     //如果当前初始化的是WebServerFactory类型的组件
    if (bean instanceof WebServerFactory) {
        this.postProcessBeforeInitialization((WebServerFactory)bean);
    }


    return bean;
}


private void postProcessBeforeInitialization(WebServerFactory webServerFactory) {
   //拿到所有定制器,然后调用每一个定制器的customize方法来给Servlet容器进行赋值
    ((Callbacks)LambdaSafe.callbacks(WebServerFactoryCustomizer.class, this.getCustomizers(), webServerFactory, new Object[0]).withLogger(WebServerFactoryCustomizerBeanPostProcessor.class)).invoke((customizer) -> {
        customizer.customize(webServerFactory);
    });
}

private Collection<WebServerFactoryCustomizer<?>> getCustomizers() {
    if (this.customizers == null) {
            //从容器中获取所有这个类型的组件:WebServerFactoryCustomizer
             //定制Servlet容器,给容器中可以添加一个WebServerFactoryCustomizer类型的组件
        this.customizers = new ArrayList(this.getWebServerFactoryCustomizerBeans());
        this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE);
        this.customizers = Collections.unmodifiableList(this.customizers);
    }


    return this.customizers;
}

ServerProperties在2.x不是定制器,变成了ServletWebServerFactoryCustomizer,然后这个定制器传入ServerProperties来获取相关配置

  

步骤:

1)、SpringBoot根据导入的依赖情况,给容器中添加相应的WebServerFactory【TomcatWebServerFactory】

2)、在ioc容器启动(创建ioc容器)的时候会调用后置处理器的postProcessBeforeInitialization方法,容器中某个组件要创建对象(TomcatWebServerFactory的实例)就会惊动后置处理器WebServerFactoryCustomizerBeanPostProcessor; postProcessBeforeInitialization是在AbstractAutowireCapableBeanFactory里的applyBeanPropertyValues方法被调用的

只要是嵌入式的Servlet容器工厂,后置处理器就工作:调用postProcessBeforeInitialization方法

3)、后置处理器从容器中获取所有的定制器,调用定制器的定制方法

posted @ 2020-05-06 17:07  hanabivvv  阅读(254)  评论(0编辑  收藏  举报