摘要:springboot项目默认以jar包方式启动运行,有时候我们可能需要以WAR的形式部署至服务器上运行,这里主要用到 SpringBootServletInitializer。
具体步骤:
1.修改项目项目启动方式,继承SpringBootServletInitializer
首先,介绍下SpringBootServletInitializer。它实现了WebApplicationInitializer接口,抽象了servlet3.0+以便通过编程的方式配置ServletContext.它将Servlet,Filter和ServletContextInitializer bean从application Context绑定到servlet容器。
你可以创建(或者修改你的启动类)一个类继承自SpringBootServletInitializer。重写config方法。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
@SpringBootApplication(scanBasePackages={"com.demo.springboot"})
public class SpringBootStandAloneWarApp extends SpringBootServletInitializer{
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SpringBootStandAloneWarApp .class);
}
public static void main(String[] args) {
SpringApplication.run(SpringBootStandAloneWarApp.class, args);
}
}
2.更新pom文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.websystique.springboot</groupId>
<artifactId>SpringBootStandAloneWarExample</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>${project.artifactId}</name>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
......
改为<packaging>war</packaging>
3.排除干扰
什么意思呢,比如说要把war放置tomcat 中运行,我们并不希望把Tomcat内嵌到war中,以避免多个相同的类冲突。只需要将scope标志为compile,即不希望它参与打包。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
4.现在你可以构建发布你的应用至外部服务器上了