maven导出项目中所有依赖jar包

maven导出项目中所有依赖jar包

开发时我们也许因为各种情况,需要导出maven的所有dependency项,如果去maven仓库找会显的相当繁琐。下面是简单的配置可以帮助我们轻松的得到所有的依赖jar。

之前使用:是使用maven-assembly-plugin 插件,发现所有依赖jar全部打到一个jar中,不能满足要求。


这里需要添加maven-dependency-plugin 这个插件。

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
</plugin>


下面主要介绍两种常见使用:<goal> 为copy,和 copy-dependencies 的情况。

1.copy

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.0.1</version>
  <configuration>
    <artifactItems>
      <artifactItem>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
      </artifactItem>
    </artifactItems>
    <outputDirectory>target/lib</outputDirectory>
  </configuration>
  <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
          <goal>copy</goal>
        </goals>
      </execution>
  </executions>
</plugin>
以上代码为copy的设置,此时需要自己指定 artifactItem (也就是需要打包的项)。outputDirectory为jar包输出目录。

此时运行maven打包命令: mvn clean package -Dmaven.test.skip=true。会在target/lib目录下生成我们配置的jar包。如下图所示:



2.copy-dependencies 。

copy-dependencies是指当前工程依赖包,它已经关联了我们pom.xml 中所有dependencies 依赖的jar。而我们不需要导出的jar包,可以用excludeArtifactIds排除,这里我们选择排除测试工具包junit 和 spring-boot-devtools 。然后同样可以指定生成目录。

spring-boot-devtools

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <version>3.0.1</version>
  <executions>
      <execution>
        <id>copy-dependencies</id>
        <phase>package</phase>
        <goals>
          <goal>copy-dependencies</goal>
        </goals>
        <configuration>
          <outputDirectory>target/lib</outputDirectory>
          <excludeArtifactIds>
            spring-boot-devtools,junit
          </excludeArtifactIds>
          <overWriteSnapshots>true</overWriteSnapshots>
        </configuration>
      </execution>
  </executions>
</plugin>


然后就可以得到我们想要的jar包了。是不是很方便了。

maven-dependency-plugin 的更多使用可以查看:http://maven.apache.org/components/plugins/maven-dependency-plugin/usage.html