Running jar, setting classpath

I have a project that I did with Maven. I am compiling the JAR with the "mvn package", and now I want to run it, preferably without installing some kind of crazy class path, as it depends on Spring and half the internet or something else. Is there a way that I can easily run it? Something like โ€œmvn runโ€ would be great, or being able to drop all the dependencies into a jar so that I can do โ€œjava -jarโ€ would also be great.

How do you deal with this, and what do you recommend doing? Since exporting CLASSPATH based on ~ / .m2 is likely to be just harmful; -)

+4
source share
3 answers

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

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 
+9
source

Setting up CLASSPATH and calling java -jar myjar.jar will not work anyway. Because the java -jar ignores the CLASSPATH environment variable, as well as the -cp flag.

In this case, you had to add entries to the path class in the jar MANIFEST using the Class-Path key, for example:

  Class-Path: jar1-name jar2-name directory-name/jar3-name 
+11
source

You need to look at the Maven build plugin . And then, once you have created the XML file needed by the plugin and modified your POM file to work with the plugin, you can run it with:

 mvn assembly:assembly 

This will create a JAR with all its dependencies.

+1
source

Source: https://habr.com/ru/post/1299253/


All Articles