Friday, June 20, 2014

Creating an executable jar file with maven

It happen to me recently that I wanted to pack a little app with maven and run it from the console, but I always forget what is the config that I need to add to maven in order to make sure the manifest pointing to the class with the main method is included.

After wasting precious half hour around the internet and after I did what I wanted to do, I thought... What better place to write this config once and remember it forever, than my blog ;)

To do it just add the following to your pom.xml and make sure you write the correct path to your main class.


 <build>  
     <plugins>  
       <plugin>  
         <artifactId>maven-assembly-plugin</artifactId>  
         <configuration>  
           <archive>  
             <manifest>  
               <mainClass>com.djordje.tips.Main</mainClass>  
             </manifest>  
           </archive>  
           <descriptorRefs>  
             <descriptorRef>jar-with-dependencies</descriptorRef>  
           </descriptorRefs>  
         </configuration>  
         <executions>  
           <execution>  
             <id>make-assembly</id>  
             <phase>package</phase>  
             <goals>  
               <goal>single</goal>  
             </goals>  
           </execution>  
         </executions>  
       </plugin>  
       <plugin>  
         <groupId>org.apache.maven.plugins</groupId>  
         <artifactId>maven-compiler-plugin</artifactId>  
         <version>2.5.1</version>  
         <inherited>true</inherited>  
         <configuration>  
           <source>1.7</source>  
           <target>1.7</target>  
         </configuration>  
       </plugin>  
     </plugins>  
   </build>  

When the maven package gets executed two .jar files will be created.
The one with the text jar-with-dependencies on its name, will contain is the one we should run. To do it, just go to the terminal, navigate to it(inside the target folder) and type the command:

 java -jar myapp-jar-with-dependencies.jar  

Share with your friends