Java 为什么Maven制作的包中没有依赖项?
我遵循并创建了以下Java 为什么Maven制作的包中没有依赖项?,java,maven,jar,Java,Maven,Jar,我遵循并创建了以下pom.xml文件: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion&g
pom.xml
文件:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>my-app</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
</project>
之后,对项目进行编译和打包:
$ mvn package
最后,我尝试运行jar文件:
$ java -cp target/my-app-1.0-SNAPSHOT.jar com.mycompany.app.App
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/JSONParser
at com.mycompany.app.App.main(App.java:11)
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.JSONParser
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
我做错了什么?根据异常
ClassNotFoundException:org.json.simple.parser.JSONParser
所需的jar
文件不在类路径中
在eclipse中,请使用以下步骤:
Right click on project --> properties --> deployment assembly --> add
--> (here select appropriate file system to add jar like)java build path entries
希望对您有所帮助。问题是,您正在将类路径设置为单个.jar文件,因此java命令无法找到依赖项。(在您的例子中是json-simple-1.1.1.jar..)
您可以告诉maven将依赖项包含在编译类的目标文件夹中
这是通过pom.xml中的以下更改完成的:
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
默认情况下,jar中不包含依赖项。您要么需要在运行时在类路径中添加所有依赖项,要么可以使用依赖项构建jar。要构建具有依赖项的jar,请参见链接:要实现包目标,阶段应为package
,然后mvn包将复制库。
<build>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>install</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
java -cp target/my-app-1.0-SNAPSHOT.jar:target/lib/json-simple-1.1.1.jar com.mycompany.app.App
{"hello":"world"}