且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Maven:项目JAR之间的包装依赖关系?

更新时间:2022-12-12 20:51:28


我喜欢Maven打包一个具有运行时依赖关系的项目。

I've like Maven to package a project with run-time dependencies.

这部分不清楚(这不完全是你之后描述的)。我的答案涵盖了你描述的内容。

This part is unclear (it's not exactly what you describe just after). My answer covers what you described.


我希望它创建一个具有以下清单的JAR文件(...)

I expect it to create a JAR file with the following manifest (...)

配置 Maven Jar Plugin (或者更准确地说, Maven Archiver ):

Configure the Maven Jar Plugin to do so (or more precisely, the Maven Archiver):

<project>
  ...
  <build>
    <plugins>
      <plugin>
         <artifactId>maven-jar-plugin</artifactId>
         <configuration>
           <archive>
             <manifest>
               <addClasspath>true</addClasspath>
               <classpathPrefix>lib/</classpathPrefix>
               <mainClass>com.acme.MainClass</mainClass>
             </manifest>
           </archive>
         </configuration>
      </plugin>
    </plugins>
  </build>
  ...
  <dependencies>
    <dependency>
      <groupId>dependency1</groupId>
      <artifactId>dependency1</artifactId>
      <version>X.Y</version>
    </dependency>
    <dependency>
      <groupId>dependency2</groupId>
      <artifactId>dependency2</artifactId>
      <version>W.Z</version>
    </dependency>
  </dependencies>
  ...
</project>

这将产生一个包含以下条目的MANIFEST.MF:

And this will produce a MANIFEST.MF with the following entries:

...
Main-Class: fully.qualified.MainClass
Class-Path: lib/dependency1-X.Y.jar lib/dependency2-W.Z.jar
...




并创建以下目录结构(...)

and create the following directory structure (...)

这可以使用 Maven Dependency Plugin 依赖关系:copy-dependencies 目标。从文档中:

This is doable using the Maven Dependency Plugin and the dependency:copy-dependencies goal. From the documentation:



  • 依赖关系:复制依赖关系 获取项目直接依赖关系的列表,可选的传递依赖关系并将它们复制到指定的位置,如果需要,剥离版本。这个目标也可以从命令行运行。

你可以在 package phase:

You could bind it on the package phase:

<project>
  [...]
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.1</version>
        <executions>
          <execution>
            <id>copy-dependencies</id>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
              <overWriteReleases>false</overWriteReleases>
              <overWriteSnapshots>false</overWriteSnapshots>
              <overWriteIfNewer>true</overWriteIfNewer>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  [...]
</project>