views:

192

answers:

3

Hi guys,

I've got a project I've made with Maven. I compile a JAR, with "mvn package", and now I want to run it, preferably without setting some insane classpath, as it depends on Spring and half the internet or something. Is there any way I can run it easily? Something like "mvn run" would be great, or an option to throw in all dependencies into the jar so I can do "java -jar" would also be splendid.

How do you deal with this, and what do you recommend doing? Because exporting a CLASSPATH based on ~/.m2 would probably just be hurtful ;-)

Cheers

Nik

+3  A: 

Use the Maven Assembly Plugin - it will automatically build your JAR with all included dependencies, and you can set the main class parameter to make the JAR executable.

The documentation can be confusing, so here is an example of what your POM will look like:

    <build>
       <plugins>
           <plugin>
               <artifactId>maven-assembly-plugin</artifactId>
               <version>2.1</version>
               <configuration>
                   <descriptorRefs>
                       <descriptorRef>jar-with-dependencies</descriptorRef>
                   </descriptorRefs>
                   <archive>
                       <manifest>
                           <mainClass>package.of.my.MainClass</mainClass>
                           <packageName>package.of.my</packageName>
                       </manifest>
                   </archive>
               </configuration>
            </plugin>
       </plugins>
   </build>

And then you can run as:

mvn assembly:assembly
danben
Thanks for the wonderful answer. The piece I was missing from this puzzle was "mvn assembly:assembly" :-)
niklassaers
+1  A: 

You will want to look into the Maven Assembly Plugin. And then once you have created the XML file required by the plugin and have modified your POM file to work with the plugin, you can run it with:

mvn assembly:assembly  

This will create the JAR with all of its dependencies.

mangoDrunk
A: 

Setting CLASSPATH and calling java -jar myjar.jar wouldn't work anyway. Because the java -jar command ignores the CLASSPATH environment variable as well as the -cp flag.

In this case you had to add the classpath entries to the jar's MANIFEST at the Class-Path key, like:

 Class-Path: jar1-name jar2-name directory-name/jar3-name
Andreas_D