spring boot 项目由jar转war
spring boot 快速构建web项目,官方推荐使用jar类型内嵌tomcat等容器的方式启动及部署,使用过程中难免要使用外部容器部署,可以通过以下方式转化:
第一步:
转化jar类型项目为可部署的war文件的第一步是提供一个SpringBootServletInitializer
子类和覆盖它的configure
方法。通常做法是,让应用程序的入口类继承SpringBootServletInitializer:
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
注意:不同版本继承的
SpringBootServletInitializer
类不同
1.3.3版本为org.springframework.boot.context.web.SpringBootServletInitializer
1.4.1版本为org.springframework.boot.web.support.SpringBootServletInitializer
第二步:
若项目使用maven并且pom.xml继承了spring-boot-starter-parent
,需要更改pom.xml中的packaging
为war
类型:
<packaging>war</packaging>
若使用Gradle
:
apply plugin: 'war'
第三步:
最后一步是确保嵌入servlet容器不干扰外部servlet容器部署war文件。需要标记嵌入servlet容器的依赖为provided
。
若使用Maven
:
<dependencies>
<!-- … -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- … -->
</dependencies>
若使用Gradle
:
dependencies {
// …
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
// …
}
若war在部署到容器中时遇到
Project facet Cloud Foundry Standalone Application version 1.0 is not supported.
错误;
解决办法: 项目右键Build Path -> Configure Build Path -> Project facet -> 勾掉Cloud Foundry Standalone Application
重新编译打包即可。
参考 :
[Spring Boot指南(Spring Boot Reference Guide)]
的以下两小节
81.1 Create a deployable war file
63.2 Packaging executable jar and war files
我是结尾。