如何在 Maven 构建期间创建包含所有模块内容的附加 jar 文件?

How to create additional jar file with contents of all modules during maven build?

我有一个多模块 Maven 项目(比如 project-xxx)。假设它由 5 个模块组成:

project-xxx (war)
--> module-1 (jar)
--> module-2 (jar)
--> module-3 (jar)
--> module-4 (jar)
--> module-5 (jar)

构建maven项目时,会生成war文件,其中包含5个模块的jar文件。

现在,为了不同的目的(即部署到分布式缓存,所以我们可以从命令行 运行 查询),我想生成一个单独的“jar”文件,其中包括java 类 来自所有模块。我知道生成多个工件是违反 Maven 的理念的,我在 SO 上阅读了这个 blog post and a few other questions

但是创建这个单一的 jar 文件会大大简化我项目中的其他一些事情。生成这个 jar 文件的最佳方法是什么?

我认为您应该考虑引入第一个单独的配置文件,以便 profile1 包含配置以产生正确的 war 打包。 Profile2 可以包含使用 maven-shade-plugin 的配置,以便从现有模块创建 UBER jar。配置文件是一种非常简洁且 maven-ish 的方式来拆分不同的关注点。

有关 Maven 配置文件,请参阅 here. For the maven-shade-plugin see here

希望对您有所帮助。

非常 非常赞成每个 Maven 项目约定一个工件。话虽这么说,如果您需要一个包含所有模块的所有 类 的 单个工件 ,那么请创建一个专用的 单个项目 这样做:

<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 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>your-group-id</groupId>
    <artifactId>one-jar-to-rule-them-all</artifactId>
    <version>your-version</version>
    <dependencies>
        <dependency>
            <groupId>your-group-id</groupId>
            <artifactId>module-1</artifactId>
            <version>your-version</version>
        </dependency>
        .
        .
        .
        <dependency>
            <groupId>your-group-id</groupId>
            <artifactId>module-5</artifactId>
            <version>your-version</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.2</version>
                <configuration>
                    <!--
                        This restricts the jar to classes from your group;
                        you may or may not want to do this.
                    -->
                    <artifactSet>
                        <includes>
                            <include>your-group-id</include>
                        </includes>
                    </artifactSet>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

此示例项目依赖于每个模块,然后使用 maven-shade-plugin 将所有这些模块组合到一个 jar 工件中。您还可以将其设为父模块 project-xxx 的子模块,以便它由反应堆构建。这样,您可以同时拥有 war 和超级 jar,但仍保持标准 Maven 构建的模块化。