如何用maven-assembly-plugin打jar-with-dependencies时排除provided传递依赖?
解决maven-assembly-plugin打包时排除传递provided依赖的问题
我来帮你搞定这个打包需求:用maven-assembly-plugin 3.1.0生成包含compile范围依赖,但自动排除传递依赖中scope为provided的jar包(比如你例子里的org.slf4j:slf4j-api:jar:1.7.16:provided)。
方案1:使用自定义Assembly描述文件(推荐,更灵活)
首先在项目的src/main/assembly目录下创建一个assembly.xml文件,内容如下:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.0.0 http://maven.apache.org/xsd/assembly-2.0.0.xsd"> <id>jar-with-dependencies</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <outputDirectory>/</outputDirectory> <useProjectArtifact>true</useProjectArtifact> <unpack>true</unpack> <!-- 只包含compile范围的依赖 --> <scope>compile</scope> <!-- 排除所有scope为provided的依赖(包括传递依赖) --> <excludes> <exclude>*:*:jar:provided</exclude> </excludes> </dependencySet> </dependencySets> </assembly>
然后在项目的pom.xml中配置maven-assembly-plugin,引用这个自定义描述文件:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.1.0</version> <configuration> <descriptors> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>make-assembly</id> <!-- 在package阶段自动执行打包 --> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
方案2:直接在Plugin中配置(无需额外文件)
如果你不想单独维护描述文件,也可以直接在plugin的配置里覆盖依赖规则:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>3.1.0</version> <configuration> <!-- 基于默认的jar-with-dependencies模板 --> <descriptorRefs> <descriptorRef>jar-with-dependencies</descriptorRef> </descriptorRefs> <dependencySets> <dependencySet> <scope>compile</scope> <!-- 排除所有provided scope的依赖 --> <excludes> <exclude>*:*:jar:provided</exclude> </excludes> </dependencySet> </dependencySets> </configuration> <executions> <execution> <id>make-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build>
验证打包结果
执行mvn clean package完成打包后,你可以用下面的命令查看生成的jar包内容,确认provided依赖已经被排除:
jar tf your-project-version-jar-with-dependencies.jar
比如你例子里的slf4j-api相关类应该不会出现在这个jar包里,而json-path、json-smart这些compile依赖会被包含在内。
内容的提问来源于stack exchange,提问作者fanf42
相关产品推荐
相关产品推荐

