Java 从其他模块导入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36916877/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:49:33  来源:igfitidea点击:

Import from other module

javamaven

提问by CeZet

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

我使用Java和编写项目Maven。在项目中我有很多模块。我的问题是我无法从其他模块导入类。

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

module1and module2are Modulesin my project, which are registred in pom.xml- main Project pom

module1并且module2Modules在我的项目,这是在registred pom.xml-主体工程POM

And when I am in Person.javafrom module1I want import the Robot.javafrom module2but I can not do this with import com.xyz.project.md2.Robot. Why ?

当我在Person.javafrommodule1我想导入Robot.javafrommodule2但我不能用import com.xyz.project.md2.Robot. 为什么 ?

采纳答案by Y.E.

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

在 module1/pom.xml 中声明对 module2 的依赖,如下所示:

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

回答by Hisham Khalil

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

必须在module1的项目中添加module2的项目作为依赖(maven依赖)。多模块并不意味着所有模块都自动相互依赖

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

Maven 中处理多模块项目的机制如下:

  • Collects all the available modules to build
  • Sorts the projects into the correct build order
  • Builds the selected projects in order
  • 收集所有可用的模块来构建
  • 将项目排序为正确的构建顺序
  • 按顺序构建选定的项目

回答by sapy

In build.gradle of module 2:

在模块 2 的 build.gradle 中:

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

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

transitive = false确保不导入依赖项的依赖项。仅导入您的源部分

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

注意 - 虽然这个问题使用 Maven,但我们大多数人使用 Gradle。