如何仅在本地测试时引入Spring Boot嵌入式Undertow依赖?
解决Spring Boot本地测试仅引入Undertow依赖的问题
问题说明
开发基于Java 11的Spring Boot应用时,本地测试使用嵌入式Undertow服务器,但预发布和生产环境部署在WAS服务器。当前生成的WAR包中包含了Undertow依赖,而该依赖仅用于本地测试,需要实现仅在本地测试阶段引入Undertow,打包时排除该依赖。
解决方案
方法一:使用Maven依赖Scope控制
修改Undertow依赖的scope为provided,该Scope表示依赖仅在编译、测试阶段可用,打包时不会被纳入WAR包,本地运行时IDE会自动加载该依赖:
<!-- undertow Server - 仅本地测试使用,打包时不包含 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> <version>${spring-boot.version}</version> <scope>provided</scope> </dependency>
同时需确保Spring Boot Web Starter排除默认的Tomcat依赖,避免容器冲突:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <!-- 排除默认Tomcat依赖 --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
方法二:使用Maven Profile区分环境
通过创建不同环境的Profile,仅在本地Profile中引入Undertow依赖,打包生产环境时切换到对应Profile即可排除该依赖:
<!-- 定义环境Profile --> <profiles> <profile> <id>local</id> <activation> <!-- 默认激活本地环境,也可通过命令行 -P local 手动激活 --> <activeByDefault>true</activeByDefault> </activation> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> <version>${spring-boot.version}</version> </dependency> </dependencies> </profile> <profile> <id>prod</id> <activation> <activeByDefault>false</activeByDefault> </activation> <!-- 生产环境无需引入Undertow依赖 --> </profile> </profiles>
- 本地运行:默认激活
localProfile,自动加载Undertow依赖 - 生产打包:执行命令
mvn clean package -P prod,生成的WAR包不包含Undertow依赖
内容的提问来源于stack exchange,提问作者user2602584
相关产品推荐
相关产品推荐

