'I added a maven project as dependency in another maven project

I added a maven project A as dependency in another maven project B and then access the jar created by B in another project through reflection, but its throwing a NoClassDefFound error for classes in maven project A

My question is, how do I make the classes in project A visible on project B's classpath? I tried adding a MANIFEST.MF but that seems to only work for jars and class files. All help appreciated.



Solution 1:[1]

Nature of a maven dependency is specified by a four-tuple (a collection of four things): GroupID, ArtifactID, version, and the often forgotten scope. The first three are collectively known as GAV of a dependency. The scope determines how the dependency is to be utilized at runtime.

In your case, what seems to be happening is that the following:

  1. Project A is compiled and installed in a local repo (e.g. using a mvn install command).
  2. In Project B's pom.xml, you specify project A's GAV as a proper <dependecy> declaration and compilation and packaging seems to go through.
  3. But since the project B's final JAR does not have project A's classes, running project B fails because A's classes are not found.

Basically, you need to tell Maven the scope of the dependency. In your case, since project A's classes are not available at a predefined runtime (e.g. Tomcat, or GlassFish web container) you need to be make sure that you bundle them with the JAR file of project B.

This is where you need a plugin attaching to a phase of build life cycle.

See maven-jar-plugin or maven-shade-plugin for details on how to make project A's classes a part of project B's final JAR file.

This assumes that you are running the classes in B as: java -jar projectB-full.jar.

Solution 2:[2]

Add commons-logging dependency to your project A (the one you are using as a dependency):

<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

Next, go to the "maven" tab, reimport dependencies, next build project A running mvn clean install. Then go to your project B, verify you have project A as a dependency (correct groupId, artifactId, and version) and reimport the dependencies. Your project B should now recognize your project A dependency.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kedar Mhaswade
Solution 2 Binyamin Regev