Home > Enterprise >  ClassNotFoundEcception when running jar through Terminal (or command prompt)
ClassNotFoundEcception when running jar through Terminal (or command prompt)

Time:10-30

So I know there are tons of questions like this one, and I have been through all of them, but I can't seem to find one like mine.

Basically, I have a java project with a lot of Maven Dependencies. The project compiles and runs just fine when I run it with IntelliJ, but now I am trying to run it through the terminal (or command prompt). In order to do that, I ran mvn package so I can get a jar file and when I run java -jar server.jar, I get the classic ClassNotFoundEcception exception. In my case, it says that it is:

Caused by: java.lang.ClassNotFoundException: org.apache.commons.fileupload.FileItemFactory

and when I suppress it by (temporarily) commenting out the part of the code that uses this class, I end up with the same error for another class. At this point, I know that I need to have some sort of folder (correct me if I'm wrong, but I believe it is called CLASSPATH) which contains the .jar of each dependency. Can anyone explain to me the situation in a clear way and how am I supposed to organize the .jar file of each dependency (if that is even what I have to do to fix my error).

CodePudding user response:

The org.apache.commons.fileupload.FileItemFactory and most likely other dependencies are not in the classpath. Intellij includes dependencies in the classpath automatically, and this is the reason it works.

To run the program from CMD with all your depedecies included define the following plugin in pom.xml:

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.1</version>
    
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    
        <executions>
            <execution>
                <id>make-assembly</id>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>
</plugins>

and run:

mvn clean package
java -jar server-jar-with-dependencies.jar
  • Related