打包后的JAR中泄漏了测试依赖项

后端开发 2026-07-08

我最近用IntelliJ的 Spring Boot项目起步器搭建了一个小型的Spring Boot应用。

在添加了两个Gatling测试依赖后,我最终得到了下面的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>4.0.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.test.dummy</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>test</description>
    <properties>
        <java.version>25</java.version>
        <gatling.version>3.14.9</gatling.version>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webmvc</artifactId>
        </dependency>

        <dependency>
            <groupId>io.gatling</groupId>
            <artifactId>gatling-app</artifactId>
            <version>${gatling.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>io.gatling.highcharts</groupId>
            <artifactId>gatling-charts-highcharts</artifactId>
            <version>${gatling.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

让我困惑的是,mvn clean package 会生成一个包含Gatling所有子依赖的jar,即使Gatling的两个依赖本身都是 <scope>test</scope>

这是怎么回事?

解决方案

你在jar中看到 netty 依赖的原因是 spring-boot-dependencies 通过 <scope>import</scope> 导入 netty-bom(在spring-boot-starter-parent上按Ctrl+点击 -> spring-boot-dependencies -> 通过 netty-bom 的artifactId搜索)。

这会在默认的 compile 作用域下把所有Netty的构件展平到 <dependencyManagement>

Gatling会以传递性方式引入Netty,按照Maven的规则,受控作用域覆盖传递作用域,因此测试依赖的作用域提升为runtime,spring-boot-maven-plugin 将Netty打包进最终的jar。

修复1 是在重新打包时排除Netty:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <excludeGroupIds>io.netty</excludeGroupIds>
    </configuration>
</plugin>

修复2 是把Gatling的测试移到一个不包含 spring-boot-maven-plugin 的独立Maven模块中。Gatling将不再参与应用模块的构建,因此作用域提升也就无法影响最终的jar。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章