简体   繁体   中英

Running jar, setting classpath

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 ;-)

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM