Wednesday, December 16, 2009

Building a self contained Jar with Maven on Netbeans

Sometimes I need to build a Jar for distribution. A typically ideal type of Jar is one which can be executed from the command line:

java -jar ./myApp.jar

I have in the past used One-Jar which works nicely for this purpose, but now I'm using Maven as standard, this should be able to do this for me. And do it without IDE dependent plugins.

Today I'm going to build a jar with Eclipse. The project which I'm building is dependent on another local Maven project, and they both are dependent on locally and repository managed Jars.

Once all the dependencies are in the Maven Classpath Container, it is a matter of editing the pom.xml file which dictates the build process.

to this I added a plugin - in the section of the node:

  <artifactid>maven-assembly-plugin</artifactid>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>net.crisppacket.myApp</mainClass>
      </manifest>
    </archive>
  </configuration>

so now, issuing (from the command line):

mvn assembly:assembly

will create a Jar for you. I got this far with the assistance of the excellent KSB's Maven Notes.

Now, in Netbeans, you can add a Custom Goal. Right click on the project you want to build, select 'Custom->Goals...' and then in the Goal field type:

assembly:assembly

OK. Now you can select this Goal (using the same mouse navigation) and it will build you a Jar. Hopefully.

No comments: