在Eclipse中将Spring Boot 3项目打WAR包并在Tomcat下部署,需要遵循以下步骤:
修改
pom.xml以支持WAR包的生成:将
<packaging>标签的值改为war。- 添加
spring-boot-starter-web依赖,并移除spring-boot-starter-tomcat依赖,因为WAR包将会在外部容器中运行。 - 创建一个继承自
SpringBootServletInitializer的类,并覆盖configure方法。 - 在Eclipse中使用Maven的
clean和package命令生成WAR包。 - 将生成的WAR包部署到Tomcat服务器中。
以下是相关的代码示例:
pom.xml修改部分:
<packaging>war</packaging>pom.xml依赖添加和移除部分:
<!-- 添加用于构建WAR包的starter-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 移除内嵌的Tomcat -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>SpringBootServletInitializer的实现:
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(YourApplication.class);
}
}在Eclipse中运行Maven命令:
mvn clean package部署到Tomcat的步骤:
- 将生成的WAR包复制到Tomcat的
webapps目录下。 - 启动Tomcat服务器。
- 访问应用,通常是通过Tomcat的端口,如
http://localhost:8080/your-app-name。
确保在部署到Tomcat之前,你已经停止了Spring Boot内嵌的Tomcat。