maven .ClassNotFoundException how to make the jar executable

1.6k Views Asked by At

I am new with Maven and I have the following problem. I have a project A which I have added as dependency in another project.

This is what I have added to my pom

</build>


  <dependencies>
  <dependency>
      <groupId>the id</groupId>
      <artifactId>artifact id</artifactId>
      <version> the version</version>
      <scope>compile</scope>
    </dependency>

In Eclipse everything is working, but when I try to open the jar file I get this message:

Caused by: java.lang.ClassNotFoundException: the name of project  A 
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 3 more

So what am I missing ? Any suggestions would be helpful

2

There are 2 best solutions below

1
On

Eclipse does its own compilations automatically in the background. The result is that your dependency's jar file is probably available in Eclipse but not in your local maven repository. Try running "maven clean install" in the terminal on your local dependency first (this will add it to your local maven repository), then afterwards build your downstream project with another "maven clean install".

This will create a jar file in the "target" directory at the root of your maven project.

0
On

When you want to run your application as:

java -jar yourapp.jar

you have take care of two things:

  1. Make sure you have your main class listed in MANIFEST.MF, which I belive you did already.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>your.package.YourMainClass</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
    
  2. Make sure that when you run you application your classpath is properly built. There are couple of ways to do that, but the easiest way would be to use the shade plugin. It will unpack all your dependencies and put them into one jar.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.3</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    

If you need the other solution without using the shade plugin, just let me know.