最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot 基于Tomcat容器的自啟動流程分析

 更新時間:2020年02月24日 09:03:49   作者:愚蠢的猴子  
這篇文章主要介紹了springboot 基于Tomcat容器的自啟動流程分析,Spring通過注解導(dǎo)入Bean大體可分為四種方式,我們主要來說Import的兩種實現(xiàn)方法,需要的朋友可以參考下

Springboot 內(nèi)置了Tomcat的容器,我們今天來說一下Springboot的自啟動流程。

一、Spring通過注解導(dǎo)入Bean大體可分為四種方式,我們主要來說以下Import的兩種實現(xiàn)方法:

1、通過實現(xiàn)ImportSerlector接口,實現(xiàn)Bean加載:

public class TestServiceImpl {
 public void testImpl() {
 System.out.println("我是通過importSelector導(dǎo)入進來的service");
 }
}
public class TestService implements ImportSelector {
 @Override
 public String[] selectImports(AnnotationMetadata annotationMetadata) {
 return new String[]{"com.ycdhz.service.TestServiceImpl"};
 }
}
@Configuration
@Import(value = {TestService.class})
public class TestConfig {
}
public class TestController {
 @Autowired
 private TestServiceImpl testServiceImpl;
 
 @RequestMapping("testImpl")
 public String testTuling() {
 testServiceImpl.testImpl();
 return "Ok";
 }
}

2、 通過實現(xiàn)ImportSerlector接口,實現(xiàn)Bean加載:

public class TestService {
 public TestService() {
 System.out.println("我是通過ImportBeanDefinitionRegistrar導(dǎo)入進來的組件");
 }
}
public class TestImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {
 @Override
 public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
 //定義一個BeanDefinition
 RootBeanDefinition beanDefinition = new RootBeanDefinition(TestService.class);
 //把自定義的bean定義導(dǎo)入到容器中
 registry.registerBeanDefinition("testService",beanDefinition);
 }
}
@Configuration
@Import(TestImportBeanDefinitionRegistrar.class)
public class TestConfig {
}

二、 Springboot啟動過程中會自動裝配

我們從spring-boot-autoconfigure-2.0.6.RELEASE.jar下搜索到Tomcat的相關(guān)配置,發(fā)現(xiàn)有兩個自動裝配類,分別包含了三個定制器(面向?qū)ο蟮膯我宦氊熢瓌t),還有一個工廠類。

2.1、TomcatWebServerFactoryCustomizer:定制Servlet和Reactive服務(wù)器通用的Tomcat特定功能。

public class TomcatWebServerFactoryCustomizer implements
 WebServerFactoryCustomizer<ConfigurableTomcatWebServerFactory>, Ordered {
 @Override
 public void customize(ConfigurableTomcatWebServerFactory factory) {
 ServerProperties properties = this.serverProperties;
 ServerProperties.Tomcat tomcatProperties = properties.getTomcat();
 PropertyMapper propertyMapper = PropertyMapper.get();
 propertyMapper.from(tomcatProperties::getBasedir).whenNonNull()
 .to(factory::setBaseDirectory);
 propertyMapper.from(tomcatProperties::getBackgroundProcessorDelay).whenNonNull()
 .as(Duration::getSeconds).as(Long::intValue)
 .to(factory::setBackgroundProcessorDelay);
 customizeRemoteIpValve(factory);
 propertyMapper.from(tomcatProperties::getMaxThreads).when(this::isPositive)
 .to((maxThreads) -> customizeMaxThreads(factory,
  tomcatProperties.getMaxThreads()));
 propertyMapper.from(tomcatProperties::getMinSpareThreads).when(this::isPositive)
 .to((minSpareThreads) -> customizeMinThreads(factory, minSpareThreads));
 propertyMapper.from(() -> determineMaxHttpHeaderSize()).when(this::isPositive)
 .to((maxHttpHeaderSize) -> customizeMaxHttpHeaderSize(factory,
  maxHttpHeaderSize));
 propertyMapper.from(tomcatProperties::getMaxHttpPostSize)
 .when((maxHttpPostSize) -> maxHttpPostSize != 0)
 .to((maxHttpPostSize) -> customizeMaxHttpPostSize(factory,
  maxHttpPostSize));
 propertyMapper.from(tomcatProperties::getAccesslog)
 .when(ServerProperties.Tomcat.Accesslog::isEnabled)
 .to((enabled) -> customizeAccessLog(factory));
 propertyMapper.from(tomcatProperties::getUriEncoding).whenNonNull()
 .to(factory::setUriEncoding);
 propertyMapper.from(properties::getConnectionTimeout).whenNonNull()
 .to((connectionTimeout) -> customizeConnectionTimeout(factory,
  connectionTimeout));
 propertyMapper.from(tomcatProperties::getMaxConnections).when(this::isPositive)
 .to((maxConnections) -> customizeMaxConnections(factory, maxConnections));
 propertyMapper.from(tomcatProperties::getAcceptCount).when(this::isPositive)
 .to((acceptCount) -> customizeAcceptCount(factory, acceptCount));
 customizeStaticResources(factory);
 customizeErrorReportValve(properties.getError(), factory);
 }
}

2.2、ServletWebServerFactoryCustomizer:WebServerFactoryCustomizer 將ServerProperties屬性應(yīng)用于Tomcat web服務(wù)器。

public class ServletWebServerFactoryCustomizer implements
 WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>, Ordered {
 private final ServerProperties serverProperties;
 public ServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
 this.serverProperties = serverProperties;
 }
 @Override
 public int getOrder() {
 return 0;
 }
 @Override
 public void customize(ConfigurableServletWebServerFactory factory) {
 PropertyMapper map = PropertyMapper.get().alwaysApplyingWhenNonNull();
 map.from(this.serverProperties::getPort).to(factory::setPort);
 map.from(this.serverProperties::getAddress).to(factory::setAddress);
 map.from(this.serverProperties.getServlet()::getContextPath)
 .to(factory::setContextPath);
 map.from(this.serverProperties.getServlet()::getApplicationDisplayName)
 .to(factory::setDisplayName);
 map.from(this.serverProperties.getServlet()::getSession).to(factory::setSession);
 map.from(this.serverProperties::getSsl).to(factory::setSsl);
 map.from(this.serverProperties.getServlet()::getJsp).to(factory::setJsp);
 map.from(this.serverProperties::getCompression).to(factory::setCompression);
 map.from(this.serverProperties::getHttp2).to(factory::setHttp2);
 map.from(this.serverProperties::getServerHeader).to(factory::setServerHeader);
 map.from(this.serverProperties.getServlet()::getContextParameters)
 .to(factory::setInitParameters);
 }
}

2.3、ServletWebServerFactoryCustomizer :WebServerFactoryCustomizer 將ServerProperties屬性應(yīng)用于Tomcat web服務(wù)器。

public class TomcatServletWebServerFactoryCustomizer
 implements WebServerFactoryCustomizer<TomcatServletWebServerFactory>, Ordered {
 private final ServerProperties serverProperties;
 public TomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {
 this.serverProperties = serverProperties;
 }
 @Override
 public void customize(TomcatServletWebServerFactory factory) {
 ServerProperties.Tomcat tomcatProperties = this.serverProperties.getTomcat();
 if (!ObjectUtils.isEmpty(tomcatProperties.getAdditionalTldSkipPatterns())) {
 factory.getTldSkipPatterns()
  .addAll(tomcatProperties.getAdditionalTldSkipPatterns());
 }
 if (tomcatProperties.getRedirectContextRoot() != null) {
 customizeRedirectContextRoot(factory,
  tomcatProperties.getRedirectContextRoot());
 }
 if (tomcatProperties.getUseRelativeRedirects() != null) {
 customizeUseRelativeRedirects(factory,
  tomcatProperties.getUseRelativeRedirects());
 }
 }
}

三、有了TomcatServletWebServerFactory,相當于有了Spring加載的入口

通過AbstractApplicationContext#onReFresh()在IOC 容器中的帶動tomcat啟動,然后在接著執(zhí)行 ioc容器的其他步驟。

我們通過斷點可以觀察Tomcat加載的整個生命周期,以及三個定制器的加載過程。

@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
 Tomcat tomcat = new Tomcat();
 File baseDir = (this.baseDirectory != null) ? this.baseDirectory
 : createTempDir("tomcat");
 tomcat.setBaseDir(baseDir.getAbsolutePath());
 Connector connector = new Connector(this.protocol);
 tomcat.getService().addConnector(connector);
 customizeConnector(connector);
 tomcat.setConnector(connector);
 //設(shè)置是否自動啟動
 tomcat.getHost().setAutoDeploy(false);
 //創(chuàng)建Tomcat引擎
 configureEngine(tomcat.getEngine());
 for (Connector additionalConnector : this.additionalTomcatConnectors) {
 tomcat.getService().addConnector(additionalConnector);
 }
 //刷新上下文
 prepareContext(tomcat.getHost(), initializers);
 //準備啟動
 return getTomcatWebServer(tomcat);
}
private void initialize() throws WebServerException {
 TomcatWebServer.logger
 .info("Tomcat initialized with port(s): " + getPortsDescription(false));
 synchronized (this.monitor) {
 try {
 addInstanceIdToEngineName();
 Context context = findContext();
 context.addLifecycleListener((event) -> {
 if (context.equals(event.getSource())
  && Lifecycle.START_EVENT.equals(event.getType())) {
  // Remove service connectors so that protocol binding doesn't
  // happen when the service is started.
  removeServiceConnectors();
 }
 });
 // Start the server to trigger initialization listeners
 this.tomcat.start();
 // We can re-throw failure exception directly in the main thread
 rethrowDeferredStartupExceptions();
 try {
 ContextBindings.bindClassLoader(context, context.getNamingToken(),
  getClass().getClassLoader());
 }
 catch (NamingException ex) {
 // Naming is not enabled. Continue
 }
 // Unlike Jetty, all Tomcat threads are daemon threads. We create a
 // blocking non-daemon to stop immediate shutdown
 startDaemonAwaitThread();
 }
 catch (Exception ex) {
 stopSilently();
 throw new WebServerException("Unable to start embedded Tomcat", ex);
 }
 }
}

備注: 在這個過程中我們需要了解Bean的生命周期,Tomcat的三個定制器均在BeanPostProcessorsRegistrar(Bean后置處理器)過程中加載;

  構(gòu)造方法-->Bean后置處理器Before-->InitializingBean-->init-method-->Bean后置處理器After

org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
 throws BeanCreationException {
 // Instantiate the bean.
 BeanWrapper instanceWrapper = null;
 if (mbd.isSingleton()) {
 instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
 }
 if (instanceWrapper == null) {
 //構(gòu)造方法
 instanceWrapper = createBeanInstance(beanName, mbd, args);
 }
 final Object bean = instanceWrapper.getWrappedInstance();
 Class<?> beanType = instanceWrapper.getWrappedClass();
 if (beanType != NullBean.class) {
 mbd.resolvedTargetType = beanType;
 }
 // Initialize the bean instance.
 ......
 return exposedObject;
}
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
 if (System.getSecurityManager() != null) {
 AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
 invokeAwareMethods(beanName, bean);
 return null;
 }, getAccessControlContext());
 }
 else {
 invokeAwareMethods(beanName, bean);
 }
 Object wrappedBean = bean;
 if (mbd == null || !mbd.isSynthetic()) {
 //Bean后置處理器Before
 wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
 }
 try {
 invokeInitMethods(beanName, wrappedBean, mbd);
 }
 catch (Throwable ex) {
 throw new BeanCreationException(
 (mbd != null ? mbd.getResourceDescription() : null),
 beanName, "Invocation of init method failed", ex);
 }
 if (mbd == null || !mbd.isSynthetic()) {
 //Bean后置處理器After
 wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
 }
 return wrappedBean;
}

總結(jié)

到此這篇關(guān)于springboot 基于Tomcat容器的自啟動流程分析的文章就介紹到這了,更多相關(guān)springboot tomcat自啟動內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 解決程序啟動報錯org.springframework.context.ApplicationContextException: Unable to start web server問題

    解決程序啟動報錯org.springframework.context.ApplicationContextExcept

    文章描述了一個Spring Boot項目在不同環(huán)境下啟動時出現(xiàn)差異的問題,通過分析報錯信息,發(fā)現(xiàn)是由于導(dǎo)入`spring-boot-starter-tomcat`依賴時定義的scope導(dǎo)致的配置問題,調(diào)整依賴導(dǎo)入配置后,解決了啟動錯誤
    2024-11-11
  • java日期工具類實例分享

    java日期工具類實例分享

    本文介紹一個java日期工具類,功能有英文簡寫、英文全稱、精確到毫秒的完整時間、中文簡寫、中文全稱等方法
    2014-01-01
  • Java中Map的遍歷方法及性能測試

    Java中Map的遍歷方法及性能測試

    這篇文章主要介紹了Java中Map的遍歷方法及性能測試,本文講解對HashMap、TreeMap進行對比測試,給出測試代碼、測試結(jié)果和測試結(jié)論,需要的朋友可以參考下
    2015-01-01
  • 詳解Java中Math.round()的取整規(guī)則

    詳解Java中Math.round()的取整規(guī)則

    這篇文章主要介紹了詳解Java中Math.round()的取整規(guī)則,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Java數(shù)組的去重

    Java數(shù)組的去重

    這篇文章主要介紹了Java數(shù)組去重,結(jié)合實例形式分析了Java針對數(shù)組的去重,需要的朋友可以參考下,希望能夠給你帶來幫助
    2021-10-10
  • SpringBoot實現(xiàn)微信支付接口調(diào)用及回調(diào)函數(shù)(商戶參數(shù)獲取)

    SpringBoot實現(xiàn)微信支付接口調(diào)用及回調(diào)函數(shù)(商戶參數(shù)獲取)

    本文詳細介紹了使用SpringBoot實現(xiàn)微信支付接口調(diào)用及回調(diào)函數(shù)的步驟,提供了代碼實現(xiàn)的具體步驟和工具類的創(chuàng)建,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • mybatis映射和實際類型不一致的問題

    mybatis映射和實際類型不一致的問題

    這篇文章主要介紹了mybatis映射和實際類型不一致的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • java基于AspectJ(面向切面編程)編碼示例分享

    java基于AspectJ(面向切面編程)編碼示例分享

    AspectJ是一種面向切面程序設(shè)計的基于Java的實現(xiàn),下面對過示例學(xué)習(xí)他的使用方法,需要的朋友可以參考下
    2014-02-02
  • MyBatis-Plus速成指南之簡化你的數(shù)據(jù)庫操作流程(最新推薦)

    MyBatis-Plus速成指南之簡化你的數(shù)據(jù)庫操作流程(最新推薦)

    MyBatis-Plus?是一個?MyBatis?的增強工具,在?MyBatis?的基礎(chǔ)上只做增強不做改變,為簡化開發(fā)、提高效率而生,這篇文章主要介紹了MyBatis-Plus速成指南:簡化你的數(shù)據(jù)庫操作流程,需要的朋友可以參考下
    2025-02-02
  • SpringMVC中的DispatcherServlet初始化流程詳解

    SpringMVC中的DispatcherServlet初始化流程詳解

    這篇文章主要介紹了SpringMVC中的DispatcherServlet初始化流程詳解,DispatcherServlet這個前端控制器是一個Servlet,所以生命周期和普通的Servlet是差不多的,在一個Servlet初始化的時候都會調(diào)用該Servlet的init()方法,需要的朋友可以參考下
    2023-12-12

最新評論

丹巴县| 深州市| 静宁县| 八宿县| 肥东县| 三江| 乌兰察布市| 内丘县| 肃宁县| 马边| 洛川县| 札达县| 合阳县| 谢通门县| 扎鲁特旗| 江城| 阳江市| 兰考县| 西乌珠穆沁旗| 项城市| 汪清县| 定边县| 郁南县| 海淀区| 江安县| 乌拉特前旗| 巨鹿县| 通辽市| 江阴市| 怀集县| 元江| 宁晋县| 莱芜市| 大悟县| 江川县| 绍兴县| 昆山市| 宿州市| 宣城市| 扎鲁特旗| 溧阳市|