在Spring Boot中生成WAR文件并部署到外部应用服务器(如Tomcat、Jetty等)时,需要进行以下几步:
- 修改
pom.xml
文件:将打包类型设置为war
,并添加必要的依赖和插件。 - 配置主应用类:使其扩展
SpringBootServletInitializer
。 - 添加
web.xml
文件(可选):在某些情况下,可能需要添加web.xml
文件。
以下是详细步骤:
1. 修改pom.xml
文件
首先,确保将打包类型设置为war
,并添加spring-boot-starter-tomcat
作为provided
依赖,以便在外部应用服务器中运行。
<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.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- 其他依赖 -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 配置主应用类
创建或修改主应用类,使其扩展SpringBootServletInitializer
,并重写configure
方法。
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(DemoApplication.class);
}
}
3. 添加web.xml
文件(可选)
在大多数情况下,Spring Boot不需要web.xml
文件。如果你确实需要一个web.xml
文件,可以将其放置在src/main/webapp/WEB-INF/
目录中。
例如:
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- 配置内容 -->
</web-app>
4. 构建WAR文件
在项目的根目录下运行以下Maven命令生成WAR文件:
mvn clean package
这将在target
目录中生成一个WAR文件,可以部署到外部应用服务器中。