Reputation: 2167
I am trying to run my first Java program, an example script that interacts with a online API (source on Github).
As it has dependencies, I follow the recommended steps using mvn test
and mvn package
, which seem to work (see output).
I however do not understand how to run the program that I just compiled (or packaged?). The .java
file contains public final class NesstarStudyLister
, so based on the pom.xml
file I try (in the base directory) the following command:
mhermans@fyr:~/tmp/nesstar-api-demo$ java -cp target/nesstar_study_lister-1.0-SNAPSHOT.jar com.nesstar.demo.NesstarStudyLister
Which results in a NoClassDefFoundError
.
How can I successfully run the small Java-program?
EDIT:
Based on the recommendation of Dave Newton, I used the Exec Maven plugin, which apparently simply consists of running
mvn exec:java -Dexec.mainClass=com.nesstar.demo.NesstarStudyLister
in the base directory, which flawlessly executes the java program.
The solution by Andriy Plokhotnyuk also works, using these commands:
(edit pom.xml to include the <build>...</build> information)
mvn package
java -jar target/nesstar_study_lister-1.0-SNAPSHOT-jar-with-dependencies.jar
Upvotes: 1
Views: 243
Reputation: 7989
Add following plugin configuration to prepare executable jar:
<project>
....
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>single</goal>
</goals>
<phase>package</phase>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<mainClass>com.nesstar.demo.NesstarStudyLister</mainClass>
</manifest>
</archive>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
...
</project>
Then goto the target directory and run:
java -jar nesstar_study_lister-1.0-SNAPSHOT-jar-with-dependencies.jar
Upvotes: 2
Reputation: 160191
The easiest way is generally the Exec Maven Plugin.
Nutshell:
You may also use Maven to create a directory with your project's dependencies (jars) and set the classpath manually, but IMO that's kind of a pain when you can use the plugin.
You may also create a jar that includes all your project's dependencies in a single file, but this may require a bit more work to explicitly include/exclude any conflicting dependencies. (With the caveat that this may be an issue with either other method as well.)
Upvotes: 2
Reputation: 3651
you need to create an executable jar file and then use java -jar filedirectory/fileName.jar
Upvotes: 0