# Maven - Create and run the jar file with dependencies

In this post, we will address two common problems.

• How to create and run the jar file generated by mvn command?

Note that the solution mentioned here may not be optimal but it should work.

mvn dependency:copy-dependencies


If we run this command, maven will download the dependency files to target/dependencies. Another way to download the dependencies is to use the maven-dependency-plugin. To use the plugin, we can copy the configuration below to the pom.xml file.

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>prepare-package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>
\${project.build.directory}/libs
</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>


In the above configuration, we can specify the output directory for the dependency files. In our case, the output directory will be target/libs.

#### Create and run the jar file

We can use the command mvn package to compile the package. This command will generate a jar file in the target folder. Note that the jar file created by maven does not contain the dependency files. Therefore, when we run the jar file, we need to add the dependencies to the class path. In our case, our dependency files are downloaded to the target/libs folder so in order to run the jar file, we should use the command below:

java -classpath "target/<jar file generated by maven>:target/libs/*" <your main class to run>


It is worth pointing out that:

• The project jar file should come before the libraries in the -classpath option.
• The separator on Mac or Linux is :.
• The dependency files are jar files. We need to include all of them by using *.

----- END -----

Want some fun stuff?