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】
只要是嵌入式的Servlet容器工厂,后置处理器就工作:调用postProcessBeforeInitialization方法
3)、后置处理器从容器中获取所有的定制器,调用定制器的定制方法