You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何maven-assembly-plugin的test scope会包含provided scope依赖?

Maven Assembly Plugin中Test Scope依赖集包含Provided依赖的原因及官方说明

当将maven-assembly-plugin的dependencySet的scope设置为test时,带有provided scope的依赖也会被加入组装包,但按预期,provided scope的依赖应该仅在明确指定时才被包含。我想了解该行为产生的原因,以及是否有官方文档对此进行说明?

最小可复现示例

pom.xml

<dependencies>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-console</artifactId>
        <version>1.10.2</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.bouncycastle</groupId>
        <artifactId>bcpkix-jdk18on</artifactId>
        <version>1.77</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>3.7.1</version>
            <executions>
                <execution>
                    <configuration>
                        <descriptors>
                            <descriptor>src/main/assembly/assembly.xml</descriptor>
                        </descriptors>
                        <finalName>maven-assembly-plugin-scopes</finalName>
                    </configuration>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>

            </executions>
        </plugin>
    </plugins>
</build>

assembly.xml

<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.2.0 https://maven.apache.org/xsd/assembly-2.2.0.xsd">
    <id>example-assembly</id>
    <formats>
        <format>jar</format>
    </formats>

    <includeBaseDirectory>false</includeBaseDirectory>

    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <unpack>true</unpack>
            <scope>test</scope>
        </dependencySet>
    </dependencySets>

</assembly>

通过上述配置,BouncyCastle(provided scope依赖)会被加入到组装后的JAR包中。

行为原因

这个问题的核心在于Maven依赖scope的生命周期激活逻辑,以及assembly-plugin对依赖集的筛选规则:

  • Maven的provided scope依赖,虽然在主代码编译、打包阶段不会被纳入,但在测试编译和测试运行阶段是会被激活并加入classpath的——因为测试环境不会像生产容器那样提供这些依赖,需要Maven主动引入以保证测试正常执行。
  • maven-assembly-plugin的dependencySet中指定scope="test"时,它筛选的是所有在Maven test阶段可用的依赖,而不是严格匹配依赖本身的scope为test。因此,所有在test阶段被激活的依赖(包括test和provided scope的依赖)都会被纳入组装包。

官方文档说明

Maven Assembly Plugin的官方文档中,关于dependencySet的scope参数有明确说明:
当scope设置为test时,插件会包含所有用于测试阶段的依赖,其中就包括provided scope的依赖——因为这些依赖在测试执行过程中是必需的,插件会默认将其纳入对应依赖集。

内容的提问来源于stack exchange,提问作者xyakimo1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:53:10