Dependencies Included!

Consider this:

What good is a phone without its battery? When we buy phones or any electronic that runs on a battery we expect batteries included with the product. 

As software developers, we face the same problem when we write Java application. We want to include dependencies with our final build. We build our project using Maven but our build won't run if we didn't to define dependencies paths for the runtime.

Maven can resolve dependencies while compiling/building the project for you but the final build in itself can't resolve dependencies unless you specify where the referenced classes are located. Here is how we typically define dependencies for the runtime:

java -cp MyProject.jar:MyCommonLibrary.jar:AnotherDependency.jar com.kondra.myproject.MainClass    

This is fine when you have a few dependencies. But that's never the case for software we write at Kondra. Most of the times we have 20 or 25 different dependencies and this means this command line will only get bigger and hard to maintain.

Luckily, there is a better solution! There is a Maven way of resolving this problem.
Recently, I had to write a script that could fetch information about Billboards Members from eBay and update our database. So I looked up for a solution to resolve this problem. I found a Maven solution to this problem. It is easy to use and can suit many use cases.
All you need to do is include this Maven configuration to your project:

<build>
      <finalName>membersUpdater</finalName>
      <plugins>
         <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
               <archive>
                  <manifest>
                     <mainClass>com.pagemage.tools.MembersUpdater</mainClass>
                  </manifest>
               </archive>
               <descriptorRefs>
                  <descriptorRef>jar-with-dependencies</descriptorRef>
               </descriptorRefs>
            </configuration>
            <executions>
               <execution>
                  <id>make-my-jar-with-dependencies</id>
                  <phase>package</phase>
                  <goals>
                     <goal>single</goal>
                  </goals>
               </execution>
            </executions>
         </plugin>
      </plugins>
   </build>

The sample maven configuration is from a pom file of membersUpdater Jar project. It has a MembersUpdater class which is defined as a mainClass in the configuration above. A main class is that class of your project that has a main(String[]) method. The Maven plugin used here is maven-assembly-plugin and can be included in your project using:

         <plugin>
               <groupId>org.apache.maven.plugins</groupId>
               <artifactId>maven-assembly-plugin</artifactId>
               <version>2.3</version>
         </plugin>


I hope you find this useful and will use this time-saving feature of Maven whenever a need arises.