Search code examples
javamavenpackaging

Why should I run a java class after generating jar file with maven package?


I'm new to jar files and maven and trying to understand the use of Maven. In this Maven in 5 minutes article, we create the my-app project using maven and the directory structure looks like this:

my-app
|-- pom.xml
 -- src
    |-- main
    |   -- java
    |       -- com
    |           -- mycompany
    |               -- app
    |                   -- App.java
     -- test
         -- java
             -- com
                 -- mycompany
                     -- app
                         -- AppTest.java

Then we use 1. mvn package followed by 2. java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App which runs our App.java class.

My understanding is that 1. creates a new 'target' directory and inside it the jar file. And we use 2. to run the App class using the jar file. My question is, why did we run the App class in this way? Why is it better than just going to src/main/java/com/mycompany/app and compiling it and running java App.java ? Maybe I don't understand benefit of packaging. Thanks for any help.


Solution

  • To know the answer of Why, you need to understand following things first:

    1. How to compile a Java program and how to run the compiled java program (especially program declared inside a package)
      If you have java class Test inside package hello, you can compile it using javac hello\Test.java and run it using java hello.Test (i.e. we use fully qualified name to run a program and can not run it like java Test, it will give you error "could not find or load main class Test")
      So, just going to src/main/java/com/mycompany/app and running java App.java won't work but from src/main/java folder you can run it like com.mycompany.app.App

    2. What is jar packaging.
      jar i.e. Java archive is nothing but a zip file aggregating all the java classes so that it can be distributed as a single unit.

    3. Classpath
      Classpath is the place where java will look for the compiled classes

    4. How to run a program which depends on Java classes in other jar files
      Suppose if my Test class depends on class XYZ which is inside the abc.jar file, then we need to tell java that search this abc.jar for dependencies (include this jar in classpath). This can be done using command java -cp abc.jar hello.Test here -cp option is nothing but a classpath and is used to tell java about directories or archives in which classes could be found. This command can be used when Test class is inside jar file like in your case

    5. Maven
      If you have understood the above things then you would know that Maven has nothing to do with running your program. It is just a build tool which helps build the jar file from you code and helps in executing/organizing different tasks apart from build like clean, running tests, etc.