Getting Started with Maven | Miscellaneous | Including Libraries When Packaging

When running package, a WAR project automatically copies dependency library files into WEB-INF/lib and includes them, even if you do not configure anything separately. In contrast, a JAR project does not include them unless you explicitly configure it.

If you need to include libraries when packaging, use the following approach.

Copying Dependency Library Files to a Specific Directory

If you run the dependency:copy-dependencies goal of the Maven Dependency Plugin, the dependency JAR library files are copied to the {project}/target/dependency directory.

mvn dependency:copy-dependencies

However, if you want them included when packaging, copying them manually every time can be cumbersome, and you may also want to copy them to a specific directory. You can configure pom.xml so dependency files are automatically copied to a specific directory when the package command runs.

<project>
   <build>
    <plugins>
      <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-dependency-plugin</artifactId>
          <version>2.3</version>
          <executions>
              <execution>
             <id>copy-dependencies</id>
              <phase>package</phase>
              <goals>
               <goal>copy-dependencies</goal>
              </goals>
            </execution>
          </executions>
         <configuration>
            <outputDirectory>../../${lib.dir}</outputDirectory>
             <overWriteIfNewer>true</overWriteIfNewer>
          </configuration>
        </plugin>
      </plugins>
    </build>
</project>

Including Dependency Library Files in the Package File

You can also create a single package file that includes all dependency files. Because all required dependency files are included, the package can be executed with only one package file and without separate classpath configuration.

First, add the Maven Assembly Plugin to pom.xml.

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.2.1</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Then run the assembly:assembly goal, and two JAR files are created under the target path. One file has no dependencies, and the other includes the dependencies.

mvn assembly:assembly

As you can tell from the file name, the file with “-jar-with-dependencies” includes the dependencies.

  • xxx-1.0.0-SNAPSHOT.jar
  • xxx-1.0.0-SNAPSHOT-jar-with-dependencies.jar

Reference