11

I'm trying to get a maven managed project to run on the command line.

I have a set of dependencies in the pom.xml which are subsequently downloaded and installed in the ~/.m2/repository/. I've included the necessary config in my pom to add the classpath to the jar manifest.

Now the problem is i'm attempting to run the jar thus: java -jar project-SNAPSHOT.jar.

Java can't find the downloaded dependencies (i'm assuming because they are listed without paths in the manifest?) , but i'm not sure how best to get this running.

Nick
  • 589
  • 1
  • 7
  • 28

2 Answers2

7

Options 1:
The jar created does not have the dependent jar files. So, you need to tell java the class-path where all the dependent jars are

    java -cp /lcoation/of/dependency1.jar:/location/of/dependency2.jar:/location/of/dependency3.jar -jar project-SNAPSHOT.jar

Option 2:
The easier and much better solution is to use AppAssembler plugin. What it does it packages your jar in a directory structure that contains

  1. dependent jars
  2. the created jar
  3. shell/windows scripts to execute it

have a look here http://www.mojohaus.org/appassembler/appassembler-maven-plugin/

Option 3:
If you do not want all the baggage and just wanted to have one jar-with-dependency You may want to refer here How can I create an executable JAR with dependencies using Maven?

This will contain all the dependent jars within it.


Edit 1: For Option 1, Brad M mentioned that you can get a list of all your project's deps using the dependency plugin. dependency:build-classpath

Community
  • 1
  • 1
Nishant
  • 54,584
  • 13
  • 112
  • 127
  • Awesome - that's exactly what I needed. Are there any caveats with packaging everything up like this or is it all ok. Memory usage etc? – Nick Oct 05 '12 at 15:30
  • No nothing. Its very simple stuffs, same as 1. making jar, 2. copying dependents in a repo folder, 3. writting a shell script that looks something like this `java -jar ../myapp.jar Mainclass -cp ../repo/*.jar` – Nishant Oct 05 '12 at 15:33
  • 2
    re Option 1, get a list of all your project's deps using the [dependency plugin](http://maven.apache.org/plugins/maven-dependency-plugin/build-classpath-mojo.html). `dependency:build-classpath` – Brad M Mar 24 '14 at 00:05
7
mvn exec:java -Dexec.mainClass="com.vineetmanohar.module.Main" -Dexec.classpathScope=runtime  

You can find more examples here: 3 ways to run Java main from Maven.

messivanio
  • 2,263
  • 18
  • 24
  • Doesn't work for me with maven 3.0.4 `[ERROR] Unknown lifecycle phase ".mainClass=my.Main"` – Brad M Mar 24 '14 at 00:02