Maven:与项目JAR一起打包依赖项?

Gil*_*ili 46 dependencies maven-2 manifest maven-assembly-plugin

我希望Maven将项目与其运行时依赖项打包在一起.我希望它使用以下清单创建一个JAR文件:

.....
Main-Class : com.acme.MainClass
Class-Path : lib/dependency1.jar lib/dependency2.jar
.....
Run Code Online (Sandbox Code Playgroud)

并创建以下目录结构:

target
|-- ....
|-- my-project.jar
|-- lib
    |-- dependency1.jar
    |-- dependency2.jar
Run Code Online (Sandbox Code Playgroud)

意思是,我希望主JAR排除任何依赖项,并且我希望所有传递依赖项都被复制到"lib"子目录中.有任何想法吗?

Pas*_*ent 65

我喜欢Maven打包一个运行时依赖项目.

这部分不清楚(这不完全是你刚才所描述的).我的回答涵盖了你所描述的.

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

配置Maven Jar插件(或者更确切地说,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>
Run Code Online (Sandbox Code Playgroud)

这将生成一个MANIFEST.MF,其中包含以下条目:

...
Main-Class: fully.qualified.MainClass
Class-Path: lib/dependency1-X.Y.jar lib/dependency2-W.Z.jar
...
Run Code Online (Sandbox Code Playgroud)

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

使用Maven Dependency Plugindependency:copy-dependencies目标是可行的.从文档:

  • dependency:copy-dependencies获取项目直接依赖项列表和可选的传递依赖项,并将它们复制到指定位置,根据需要剥离版本.也可以从命令行运行此目标.

你可以在package阶段绑定它:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 即使在为依赖插件指定上述配置之后,我也会在默认的'dependency'文件夹中获取所有jar.在包装'MANIFEST.MF'上有主类和类路径,但最终jar中没有包装依赖jar. (3认同)