springboot的web项目如何打成war包

Spring Boot通常提倡将项目打成jar包以命令行方式运行,但有时也需打成war包放进web容器。本文介绍了将Spring Boot项目打包成war包的方法,包括修改pom文件打包方式、打包排除tomcat依赖以及让主类继承SpringBootServletInitializer并实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

虽然springboot提倡把项目打成jar包,然后以命令行的方式运行。但偶尔也有需要打成war放进tomcat等web容器中运行。

1. 修改pom文件打包方式为war
<packaging>war</packaging>
2. 打包排除tomcat依赖

添加依赖,依赖范围设置为provided,在使用tomcat容器时就不会使用该依赖,避免发生冲突

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

scope:
This element refers to the classpath of the task at hand (compiling and runtime, testing, etc.) as well as how to limit the transitivity of a dependency. There are five scopes available:
compile - this is the default scope, used if none is specified. Compile dependencies are available in all classpaths. Furthermore, those dependencies are propagated to dependent projects.
provided - this is much like compile, but indicates you expect the JDK or a container to provide it at runtime. It is only available on the compilation and test classpath, and is not transitive.
runtime - this scope indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.
test - this scope indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases. It is not transitive.
system - this scope is similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.

provided : 该范围和compile很像,它表示你希望在项目运行时由JDK或容器来提供这个依赖.它仅仅在测试和编译时使用,并且该范围的依赖不具有传递性.

3. 继承SpringBootServletInitializer

让springboot项目的主类继承SpringBootServletInitializer,并实现configure方法

@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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值