CeZet
CeZet

Reputation: 1513

Import from other module

I write project using Java and Maven. In project I have many modules. My problem is that I can not import classes from other module.

My project structure looks like this:

Project
 |_ module1
    |_ src
       |_ com.xyz.project.md1
          |_ Person.java
    |_ pom.xml <- pom of module1
 |_ module2
    |_ src
       |_ com.xyz.project.md2
          |_ Robot.java
    |_ pom.xml <- pom of module2
 |_ pom.xml <- main Project pom

module1 and module2 are Modules in my project, which are registred in pom.xml - main Project pom

And when I am in Person.java from module1 I want import the Robot.java from module2 but I can not do this with import com.xyz.project.md2.Robot. Why ?

Upvotes: 28

Views: 47874

Answers (3)

Hisham Khalil
Hisham Khalil

Reputation: 1084

You have to add the project of module2 as dependency (maven dependency) in the project of module1. multimodules doesn't mean that all modules have automatically dependency to each other

The mechanism in Maven that handles multi-module projects does the following:

  • Collects all the available modules to build
  • Sorts the projects into the correct build order
  • Builds the selected projects in order

Upvotes: 3

sapy
sapy

Reputation: 9584

In build.gradle of module 2:

dependencies {
    compile(project(":module1")) {
        transitive = false
    }
     ...
     //Other dependencies
     ...
}

transitive = false ensures dependencies of dependencies are not imported . Only your source part is imported

N.B. - Though the question uses Maven, but most of us use Gradle.

Upvotes: 2

Y.E.
Y.E.

Reputation: 922

Declare dependency to module2 in module1/pom.xml, something like this:

<dependencies>
    ...
            <dependency>
                <groupId>XX</groupId>
                <artifactId>module2</artifactId>
                <version>0.0.1-SNAPSHOT</version>
            </dependency>
    ...
</dependencies>

Upvotes: 39

Related Questions