简体   繁体   English

如何获得同级Maven项目的jar工件的路径?

[英]how to get a path to a sibling maven project's jar artifact?

I have a java console based application that is created as a jar file and is run using: 我有一个基于Java控制台的应用程序,该应用程序创建为jar文件,并使用以下命令运行:

java -jar commandlineapp.jar

The application is built using maven. 该应用程序是使用maven构建的。 I have a junit test project that is also a maven project, ie 我有一个junit测试项目,它也是一个Maven项目,即

parent
+- pom.xml
+- commandlineapp
|  +-pom.xml
+- commandlineapp_test
   +pom.xml

The test project has a dependency on the commandlineapp to ensure that the app is built prior to running the test. 测试项目对commandlineapp有依赖性,以确保在运行测试之前已构建该应用。

The test project has some junit unit tests that execute the commmandlineapp using ProcessBuilder . 该测试项目具有一些junit单元测试,这些单元测试使用ProcessBuilder执行ProcessBuilder Eg 例如

String jarfile = 
 "C:\\Users\\me\\.m2\\repository\\my\\org\\commandlineapp\\0.0.1-SNAPSHOT\\commandlineapp-.0.1-SNAPSHOT.jar";

ProcessBuilder pb = new ProcessBuilder("java", "-jar", jarFile);

At the moment, you can see that I have a hard-coded path to the commandlineapp jar file. 目前,您可以看到我有一个到commandlineapp jar文件的硬编码路径。

Question: is there some meta data that I can use to look up jar path for the sibling project? 问题:是否有一些元数据可用于查找同级项目的jar路径? Ideally, I would still like to be able to run the unit tests from eclipse in addition to running them from maven. 理想情况下,除了从maven运行之外,我仍然希望能够从eclipse运行单元测试。

One way is to use the maven dependency plugin in the test project to copy the commandlineapp (and its dependencies) to the test project: 一种方法是在测试项目中使用maven依赖插件将commandlineapp(及其依赖项)复制到测试项目中:

     <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
           <execution>
              <phase>process-test-resources</phase>
              <goals>
                 <goal>unpack-dependencies</goal>
              </goals>
              <configuration>
                 <outputDirectory>${project.build.directory}/lib</outputDirectory>
              </configuration>
           </execution>
        </executions>
     </plugin>

Then from within the test project, you can get access to the target folder: 然后从测试项目中,您可以访问目标文件夹:

File testClassesFolder = 
   new File(CommandLineAppTest.class.getClassLoader().getResource(".").getFile());

We need to create a string with the class path. 我们需要使用类路径创建一个字符串。 The classpath 类路径

String classPath = testClassesFolder.getParent() + File.separator + "lib";

Then pass this to ProcessBuilder: 然后将其传递给ProcessBuilder:

ProcessBuilder pb = 
  new ProcessBuilder(
     javaExecutablePath, "-cp", classPath, "my.org.CommandLineApp"
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM