springboot中如何利用Tomcat容器實現自啟動
一、Spring透過註解導入Bean大體可分為四種方式,我們主要來說以下Import的兩種實作方法:
1、透過實作ImportSerlector接口,實作Bean載入:
public class TestServiceImpl { public void testImpl() { System.out.println("我是通过importSelector导入进来的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、 透過實作ImportSerlector接口,實作Bean載入:
public class TestService { public TestService() { System.out.println("我是通过ImportBeanDefinitionRegistrar导入进来的组件"); } } public class TestImportBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { @Override public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) { //定义一个BeanDefinition RootBeanDefinition beanDefinition = new RootBeanDefinition(TestService.class); //把自定义的bean定义导入到容器中 registry.registerBeanDefinition("testService",beanDefinition); } } @Configuration @Import(TestImportBeanDefinitionRegistrar.class) public class TestConfig { }
二、 Springboot啟動過程中會自動組裝
我們從spring-boot-autoconfigure-2.0.6.RELEASE .jar下搜尋到Tomcat的相關配置,發現有兩個自動裝配類,分別包含了三個定制器(面向對象的單一職責原則),還有一個工廠類。
2.1、TomcatWebServerFactoryCustomizer:客製化Servlet和Reactive伺服器通用的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); } }</configurabletomcatwebserverfactory>
2.2、ServletWebServerFactoryCustomizer:WebServerFactoryCustomizer 將ServerProperties屬性套用到Tomcat web伺服器。
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); } }</configurableservletwebserverfactory>
2.3、ServletWebServerFactoryCustomizer :WebServerFactoryCustomizer 將ServerProperties屬性套用到Tomcat web伺服器。
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>
三、有了TomcatServletWebServerFactory,相當於有了Spring載入的入口
透過AbstractApplicationContext#onReFresh()在IOC 容器中的帶動tomcat啟動,然後在接著執行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); //设置是否自动启动 tomcat.getHost().setAutoDeploy(false); //创建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後置處理器)過程中載入;
建構方法-->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) { //构造方法 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; }</object>
以上是springboot中如何利用Tomcat容器實現自啟動的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

若要將 JAR 專案部署到 Tomcat,請遵循以下步驟:下載並解壓縮 Tomcat。配置 server.xml 文件,設定連接埠和專案部署路徑。將 JAR 檔案複製到指定的部署路徑中。啟動 Tomcat。使用提供的 URL 存取已部署的項目。

要讓 Tomcat 伺服器對外網訪問,需要:修改 Tomcat 設定文件,允許外部連接。新增防火牆規則,允許存取 Tomcat 伺服器連接埠。建立 DNS 記錄,將網域名稱指向 Tomcat 伺服器公有 IP。可選:使用反向代理提升安全性和效能。可選:設定 HTTPS 以提高安全性。

Tomcat 安裝目錄:預設路徑:Windows:C:\Program Files\Apache Software Foundation\Tomcat 9.0macOS:/Library/Tomcat/Tomcat 9.0Linux:/opt/tomcat/tomcat9自訂路徑:安裝時可指定。尋找安裝目錄:使用 whereis 或 locate 指令。

要透過 Tomcat 部署多個項目,需要建立每個專案的 webapp 目錄,然後:自動部署:將 webapp 目錄放置在 Tomcat 的 webapps 目錄中。手動部署:在 Tomcat 的 manager 應用程式中手動部署專案。專案部署後,可以透過其部署名稱訪問,例如:http://localhost:8080/project1。

查看Tomcat並發連線數的方法:造訪Tomcat Manager頁面(http://localhost:8080/manager/html),輸入使用者名稱和密碼。在左側導覽列中點選Status->Sessions,即可在頁面頂部看到並發連線數。

Tomcat 網站根目錄位於 Tomcat 的 webapps 子目錄中,用於儲存 Web 應用程式檔案、靜態資源和 WEB-INF 目錄;它可以透過尋找 Tomcat 設定檔中的 docBase 屬性來找到。

Tomcat埠號碼可透過以下方法檢視:檢查server.xml檔案中的<Connector>元素的port屬性。造訪Tomcat管理介面(http://localhost:8080/manager/html)並查看"Status"標籤。在命令列中運行"catalina.sh version"並查看"Port:"行。

若要設定 Tomcat 使用域名,請執行下列步驟:建立伺服器.xml 備份。開啟 server.xml 並加入 Host 元素,將 example.com 替換為你的網域。為網域名稱建立 SSL 憑證(如果需要)。在 server.xml 中新增 SSL 連接器,變更連接埠、金鑰庫檔案和密碼。保存 server.xml。重新啟動 Tomcat。
