How to share code between two projects?

Tags: , , ,



I have two Java projects called A and B. Both of them are web apps deployed as war files. I created them in Eclipse workspace separately. Project B uses a class in project A named MusicMapper. I added the project A to project B’s build path in Eclipse as suggested in this post. So now project B can compile without any errors and the class MusicMapper can be seen in project B by importing it in project B:

import com.projectA.MusicMapper;

Everything seems to be fine before I launched the web app of project B. However, when I launched the project B and called the code that references class MusicMapper in project A, I got the following runtime error:

java.lang.ClassNotFoundException: com.projectA.MusicMapper

So this error seems to be caused by unfound class com.projectA.MusicMapper which is imported from project A. Since I already added project A to project B build path and project B compiles fine without any errors, why does it report this error at runtime?

Another approach I took was: I’ve also tried using the following Maven import in project B’s pom.xml:

    <dependency>
        <groupId>com.projectA</groupId>
        <artifactId>projectA</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <scope>system</scope>
        <systemPath>/path/to/projectA.jar</systemPath>
    </dependency>

where projectA.jar is the jar file I exported from project A. But it still gave me the same ClassNotFoundException. How can I make the class in project A usable by project B? It seems that neither of the two approaches I’ve tried works.

Answer

First of all if you have two projects which are both deployed as wars it’s not a good idea to include one project into another as a dependency. Because you will be puling in lot of other stuff that you don’t need in project B.

A better approach will be to create a Third java project lets say “Common” this should be just a java project and NOT a Dynamic Web Project and should compile as a jar. Move all the stuff that is shared between Project A and Project B into Common project.

Now back your problem Just adding some thing in project build path in eclipse does not mean you have added the dependency to your project outside of eclipse as well. Eclipse don’t complain because it can resolve and find the project because you added in eclipse build path. You will have to compile common dependency project using some build tool like ant, maven or gradle and package the jar in your war file when war is built.

If you don’t want to use a build tool a simple route would be just export the third project from eclipse as jar. Copy the common jar file in WEB-INF/lib folder of your Project A and Project B before you export the war file from your eclipse.

I hope it helps 🙂



Source: stackoverflow