【问题标题】:maven include main project into test-jarmaven 将主项目包含在 test-jar 中
【发布时间】:2017-11-06 16:20:21
【问题描述】:

我已经用 maven-jar-plugin 创建了一个 test-jar

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-jar-plugin</artifactId>
    <version>2.4</version>
    <executions>
        <execution>
            <goals>
                <goal>test-jar</goal>
            </goals>
        </execution>
    </executions>
</plugin>

但是 test-jar 需要主类才能工作,那么我怎样才能将它们包含在 test-jar 中(创建类似 uber-test-jar 的东西)?

【问题讨论】:

    标签: java maven jar maven-plugin


    【解决方案1】:

    通常我两次导入依赖:

    1. 常规的;
    2. 范围 = 测试的测试罐。

    这样您就不会遇到缺课的问题。但是,如果您的应用程序中不需要主源(第一个依赖项)并且它们仅用于测试,您也可以将其范围切换为测试。

    <scope>test</scope>
    

    【讨论】:

    • 我不需要导入任何类,我只是在构建 jar,因为我需要在另一个应用程序中将 test-jar 作为插件进行测试
    • 嗯? test-jar 作为另一个应用程序中的插件?对我来说听起来不对。我本来希望测试 jar 而不是 test-jar?
    • 我通常使用它,当我需要从另一个模块导入一些实用程序测试类时。这些类非常有用,因此它们在模块之间共享。同时,它们无法在主代码中访问。
    【解决方案2】:

    您不能通过 maven-jar-plugin 将其他类添加到 test-jar,但您可以通过另一种方式创建包含主要项目类和测试类的 jar:使用 maven-assembly-plugin!

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
            <descriptor>src/assembly/dep.xml</descriptor>
        </configuration>
        <executions>
            <execution>
                <id>create-archive</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
    

    这将使用程序集描述符中描述的信息创建一个工件,描述符默认路径是 src/assembly/.xml 在要添加的描述符中:

    <assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-  plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
        <id>example</id>
        <formats>
            <format>jar</format>
        </formats>
        <includeBaseDirectory>false</includeBaseDirectory>
        <fileSets>
            <fileSet>
                <directory>${project.build.testOutputDirectory}</directory>
                <outputDirectory>/</outputDirectory>
            </fileSet>
            <fileSet>
                <directory>${project.build.outputDirectory}</directory>
                <outputDirectory>/</outputDirectory>
            </fileSet>
        </fileSets>
    </assembly>
    
    • id -> jar 的后缀
    • 格式 -> 输出文件的格式(我们正在创建一个 jar)
    • fileSets -> 所有要添加的目录
    • fileSet -> 要添加的单个目录,带有 outputDirectory,包括排除 ecc。

    此示例将创建一个带有 -example 作为后缀的 jar(例如:plugin-1.0-example.jar),其中包含主文件和测试文件

    【讨论】:

      猜你喜欢
      • 2014-02-05
      • 1970-01-01
      • 2016-06-23
      • 2018-12-19
      • 1970-01-01
      • 2021-01-19
      • 2017-09-12
      • 2015-05-14
      • 2013-03-20
      相关资源
      最近更新 更多