Saturday, November 14, 2020

Java - Copy project dependency (jars) to a folder using Maven Plugin

If one have to execute a Java program from Command prompt then it would be cumbersome to specify all the required Jar files. It would be very easy to specify the jars if all of them are in a single folder. Using a Maven Plugin we can easily copy all the dependency jars to a specific folder and then execute a Java class easily

  • Use the following Maven plug-in, mention the target folder in <outputDirectory> element, currently the folder is target/jars
 <plugin>  
      <groupId>org.apache.maven.plugins</groupId>  
      <artifactId>maven-dependency-plugin</artifactId>  
      <version>3.1.2</version>  
      <executions>  
           <execution>  
                <id>copy-dependencies</id>  
                <phase>package</phase>  
                <goals>  
                     <goal>copy-dependencies</goal>  
                </goals>  
                <configuration>  
                     <outputDirectory>${project.build.directory}/jars</outputDirectory>  
                     <overWriteReleases>false</overWriteReleases>  
                     <overWriteSnapshots>false</overWriteSnapshots>  
                     <overWriteIfNewer>true</overWriteIfNewer>  
                </configuration>  
           </execution>  
      </executions>  
 </plugin>  
  • Execute the command mvn clean package
  • Above command should have copied all the dependency jars under target/jars folder


  • To run a Java program from the jar use the following command
 java -cp target/<YOUR_PROJECT_JAR>:target/jars/* <class_to_be_run>  
  • For example to execute Java Class DynamoDBDisableStream.java issue this command
 java -cp target/aws-java-0.0.1-SNAPSHOT.jar:target/jars/* com.balatamilmani.awsdemo.dynamodb.DynamoDBDisableStream  

Reference: https://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-project-dependencies.html

No comments:

Post a Comment