我的项目在 IntelliJ IDEA 中运行良好,同时遇到来自 CLI 工具的 java.lang.ClassNotFoundException,我该如何解决?

时间:2021-05-16 01:55:44

标签: java maven intellij-idea

我做了什么

我使用 IntelliJ IDEA 创建了一个 maven 项目,遵循 tutorial

JDK11 中的小项目是(为我自己)演示如何com.google.code.gson 将对象序列化为 json 字符串。

这个项目的 POM 是:

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mig</groupId>
    <artifactId>mia</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--  Gson: Java to Json conversion -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>
    
    <properties>
        <maven.compiler.release>11</maven.compiler.release>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

</project>

Employee.java 中,我确实生成了 setter 和 getter,但我没有将它们放在这里以节省空间。

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;
   private List<String> roles;
    
   public Employee(){      
   }
    
   public Employee(Integer id, String firstName, String lastName, Date birthDate){
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }
    
   //Getters and setters
    
   @Override
   public String toString()
   {
      return "Employee [id=" + id + ", firstName=" + firstName + ", " +
            "lastName=" + lastName + ", roles=" + roles + "]";
   }
}

O2Json.java

package mig;

import java.util.Arrays;
import com.google.gson.*;

public class O2Json {
    public static void main(String[] args) throws Exception{
        Employee employee = new Employee();
        employee.setId(1);
        employee.setFirstName("Lokesh");
        employee.setLastName("Gupta");
        employee.setRoles(Arrays.asList("ADMIN", "MANAGER"));
        System.out.println(employee.toString());

        Gson gson = new Gson();
        System.out.println(gson.toJson(employee));
    }
}

项目由以下标准项目结构组成

mvn_idea 
├── pom.xml
└── src
    ├── main
    │   ├── java
    │   │   ├── Employee.java
    │   │   └── O2Json.java
    │   └── resources
    └── test
        └── java

当我使用 IDEA 的运行菜单命令运行应用程序时,我的 Mac 上的 IntelliJ IDEA 一切正常。

enter image description here

此命令使用 IntelliJ IDEA 生成可执行 JAR

/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home/bin/java -Dmaven.multiModuleProjectDirectory=/Users/ubuntu/sourcecode/mvn_idea "-Dmaven.home=/Applications/IntelliJ IDEA CE.app/Contents/plugins/maven/lib/maven3" "-Dclassworlds.conf=/Applications/IntelliJ IDEA CE.app/Contents/plugins/maven/lib/maven3/bin/m2.conf" "-javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=65438:/Applications/IntelliJ IDEA CE.app/Contents/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/IntelliJ IDEA CE.app/Contents/plugins/maven/lib/maven3/boot/plexus-classworlds-2.5.2.jar" org.codehaus.classworlds.Launcher -Didea.version2019.1.3 install

但是,这种方法在我通过 SSH 连接的 Ubuntu 服务器上并不方便。

所以我尝试使用命令行工具 mvn 来完成这项工作。

mvn package 似乎运行良好

[INFO] Building jar: /Users/ubuntu/sourcecode/mvn_idea/target/mia-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 01:13 min
[INFO] Finished at: 2021-05-16T09:41:04+08:00
[INFO] Final Memory: 18M/74M
[INFO] ------------------------------------------------------------------------

但是,当我尝试运行该应用程序时,出现错误

$ java -cp target/mia-1.0-SNAPSHOT.jar mig.O2Json
mig.Employee [id=1, firstName=Lokesh, lastName=Gupta, roles=[ADMIN, MANAGER]]
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gson/Gson
    at mig.O2Json.main(O2Json.java:15)
Caused by: java.lang.ClassNotFoundException: com.google.gson.Gson
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:636)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:182)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:519)
    ... 1 more

问题

我该如何解决这个错误?

更新

这是新版本的POM

<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mig</groupId>
    <artifactId>mia</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!--  Gson: Java to Json conversion -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
    </dependencies>

    <properties>
        <maven.compiler.release>11</maven.compiler.release>
    </properties>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>

            </plugins>
        </pluginManagement>
    </build>

</project>

我执行了 mvn cleanmvn packagejava -cp target/mia-1.0-SNAPSHOT.jar mig.O2Json 并得到了同样的错误。

我也试过 mvn clean compile assembly:singlejava -cp target/mia-1.0-SNAPSHOT.jar mig.O2Json 并得到同样的错误。

1 个答案:

答案 0 :(得分:1)

您需要告诉 maven 包含依赖项。当 IntelliJ 为您运行它时,它会将所有依赖项添加到类路径中,这就是它在 IntelliJ 中工作的原因。

Try this

如果您运行 mvn package 并使用更新后的 pom.xml 解压生成的 jar,您将看到依赖项仍未包含在内。

这样做的原因是你需要把

                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>

    <build>
        <plugins>
                <plugin>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>package</phase>
                            <goals>
                                <goal>single</goal>
                            </goals>
                        </execution>
                    </executions>
                    <configuration>
                        <descriptorRefs>
                            <descriptorRef>jar-with-dependencies</descriptorRef>
                        </descriptorRefs>
                    </configuration>
                </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.1</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

不在 pluginManagement 中。 我试过了,它生成了一个名为 ...-with-dependencies 的 jar,然后你的 java 命令运行良好。