前言
springBoot項目開發過程中使用的是內嵌的tomcat,jetty容器,當項目需要發布的時候怎麼呢。
只需要兩步 步驟 修改啟動類,繼承 SpringBootServletInitializer 並重寫 configure 方法
/** * Author: 遇見小星 * Email: tengxing7452@163.com * Date: 17-5-10 * Time: 上午10:40 * Describe: 程式入口 */@SpringBootApplication@EnableAutoConfigurationpublic class Mainspringboot extends SpringBootServletInitializer {@Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Mainspringboot.class); }
修改pom.xml檔案
<!-- <packaging>jar</packaging> --> <packaging>war</packaging>
tomcat外掛程式依賴包添加生命週期privided
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency>
結束語
SpringBootServletInitializer類implements WebApplicationInitializer介面,而WebApplicationInitializer裡有void onStartup(ServletContext var1) 方法
void onStartup(ServletContext var1) throws ServletException;
SpringBootServletInitializer 實現了這個onStartup方法,主要在啟動容器時負責載入相關配置
public void onStartup(ServletContext servletContext) throws ServletException { this.logger = LogFactory.getLog(this.getClass()); final WebApplicationContext rootAppContext = this.createRootApplicationContext(servletContext); if(rootAppContext != null) { servletContext.addListener(new ContextLoaderListener(rootAppContext) { public void contextInitialized(ServletContextEvent event) { } }); } else { this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not return an application context"); } }
代碼
servletContext.addListener(new ContextLoaderListener(rootAppContext) { public void contextInitialized(ServletContextEvent event) { } });
中ContextLoaderListener實現了ServletContextListener介面,這樣就可以通過addListener()的方式將springboot項目下的相關配置進行載入。