如何在Maven项目中处理CLASSPATH? [英] How to handle with CLASSPATH in Maven project?
问题描述
我正在尝试使用Log4J ver 2-beta 9的简单Maven应用程序。在我的pom.xml文件中,我有这两个依赖项(如 Log4J Maven网页):
I am trying simple Maven app with Log4J ver 2-beta 9. In my pom.xml file I have these two dependencies (as is mentioned in Log4J Maven webpage):
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta9</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta9</version>
</dependency>
Eclipse看到Log4J库:
Eclipse sees Log4J library:
< img src =https://i.stack.imgur.com/mHp2S.pngalt =在此处输入图像说明>
但是当我打包应用程序时并运行它抛出异常:
But when I package the app and run it this Exception is thrown:
java -cp target/notification-1.0.0.jar com.example.Sandbox
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/LogManager
at com.example.Sandbox.<clinit>(Sandbox.java:13)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.LogManager
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 1 more
<我搜索了这个异常,它似乎与CLASSPATH变量有关。
I searched for this Exception and it seems to be related to CLASSPATH variable.
如何为Maven项目设置CLASSPATH?
推荐答案
Maven是一个构建工具。它对运行最终应用程序没有帮助。
Maven is a build tool. It doesn't help you much running the final application.
您可以使用 mvn exec:java -Dexec。 mainClass =com.example.Sandbox
运行你的应用程序(参见问题 Maven Run项目)但是当你必须向它传递参数时,这会很繁琐。
You can use mvn exec:java -Dexec.mainClass="com.example.Sandbox"
to run your app (see the question Maven Run Project) but this gets tedious when you have to pass arguments to it.
你可以使用<$ c来获取Maven用于编译应用程序的类路径$ c> mvn依赖:build-classpath
这会将类路径打印到控制台。请注意,它将丢失 target / notification-1.0.0.jar
That will print the classpath to the console. Note that it will be missing target/notification-1.0.0.jar
此领域的另一个有用工具是程序集插件;当你指定描述符 jar-with-dependencies
时,它会创建一个非常大的JAR,并将所有依赖项归为一个文件。
Another useful tool in this area is the assembly plugin; it will create one very big JAR with all the dependencies rolled into a single file when you specify the descriptor jar-with-dependencies
.
这篇关于如何在Maven项目中处理CLASSPATH?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!