Tuesday 2 April 2013

Creating an executable jar with a Maven plugin

While there are several non Maven based ways of creating an executable Jar that includes all required dependencies, Maven as a build tool offers three plugins for directly achieving this result. The Maven Assembly plugin is the first of these options. Creating an executable jar is just one of the objectives of the Assembly plugin. It can be used to create distributions in various file formats such as the zip format.
To configure the Maven Assembly plugin to create an executable jar with all required dependencies included, add the following configuration definition to your pom.xml in the build section.



   ..........
   
   maven-assembly-plugin
   2.4
   
     false
         standalone-${artifactId}-${version}
     
       jar-with-dependencies
     
     
        
           com.data.john.MainClass
           true
        
     
   
     
        
           make-assembly 
           package
           
              single
           
        
    
 
.............
.............


The second option is the Maven Shade plugin. The primary objective of this plugin is to create an executable jar and so it is much more suited for this use case. The configuration setup is as follows:



.................   

    org.apache.maven.plugins
    maven-shade-plugin
    2.0
    
        
             package
            
                 shade
            
            
            standalone-${artifactId}-${version}
            
              
              *:*
              
               META-INF/*.SF
               META-INF/*.DSA
               META-INF/*.RSA
              
             
            
            
                 
                    com.data.masker.controller.MaskerApp
                
            
           
        
    

..............




While tossing up between the Assembly and the Shade plugin, It should be mentioned that with using Maven Assembly, you run the risk of overwriting files with similar namespaces. These scenarios can be better handled using the Shade plugin, that provides more granular control over the build process by merging files with the same name instead of overwriting them.
Finally, this discussion would not be complete without mentioning the Maven Jar plugin, yet another way of  creating an executable jar with some use case examples given here.
All three options can be invoked using the mvn package call. 

No comments: