spring-boot-tomcat
阿新 • • 發佈:2018-12-06
外部的Tomcat伺服器部署war包
1.繼承SpringBootServletInitializer
外部容器部署的話,就不能依賴於Application的main函數了,而是要以類似於web.xml檔案配置的方式來啟動Spring應用上下文,此時我們需要在啟動類中繼承SpringBootServletInitializer並實現configure方法:
public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } }
這個類的作用與在web.xml中配置負責初始化Spring應用上下文的監聽器作用類似,只不過在這裡不需要編寫額外的XML檔案了。
2.pom.xml修改tomcat相關的配置
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
在這裡需要移除對嵌入式Tomcat的依賴,這樣打出的war包中,在lib目錄下才不會包含Tomcat相關的jar包,否則將會出現啟動錯誤。
設定為provided,這種方式的好處是,打包的war包同時適合java -jar命令啟動以及部署到外部容器中。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency>