Including Dependencies in a Java Console Application

We created a Java Module that retrieves data from MySQL and want to run it at the command line.  To do so we have the mysql-connector-java-5.1.26-bin.jar external library with its com.mysql.jbdc class module that we need to reference.  In IntelliJ IDEA we see our dependency in the Project’s External Libraries folder.

We touched on referencing external class modules before in ClassNotFoundException com.mysql.jdbc.Driver fix in IntelliJ IDEA. That solution only addresses the IntelliJ IDEA Run Window.  Here is the before and after on that from the original post.

Here’s what happens when we compile and run the program using our Linux machine’s JVM at the Command Line.

Look familiar?

A JAR for a JAR

It turns out what we have to do is create a Java Archive (JAR) file. More specifically, we need to create a Java Artifact in IntelliJ IDEA.  We can then go to the command line and execute the program with its dependencies using the syntax

java -jar myapp.jar

Much delight and giggling with the successful execution of the Java application will no doubt follow!

To create our artifact we start in File -> Project Structure and add a Jar Artifact.

Here’s the config dialog…

…with the resulting artifact looking something like this.

Our final step is to build our artifact.

Now we can go to our command line a execute our .jar artifact with

java -jar myapp.jar

What a Pretty Console Application!