Menu Close

使用 Gradle 构建 Java 多模块项目(例四)

环境描述

描述项 内容
操作系统 CentOS Linux release 7.8.2003 (Core)
java版本 java version "1.8.0_161"
IDEA版本 2022.2.2
Gradle版本 7.5

1. 示例1:各子项目单独配置

1.1. 创建主项目目录

mkdir multiModule

1.2. 进入主项目目录

cd multiModule

以下操作均在该目录下完成。

1.3. 创建 settings.gradle 与 build.gradle文件

touch ./settings.gradle
touch ./build.gradle

其中 build.gradle 文件内容为空。

1.4. 运行 gradle wrapper 命令

gradle wrapper

1.5. 创建子项目目录

# 创建子项目 child1
mkdir -p ./child1/src/main/java/xin/qishuo/child1/
# 创建子项目 child2
mkdir -p ./child2/src/main/java/xin/qishuo/child2/

1.6. 子项目child1的配置

1)创建一个java类

vim ./child1/src/main/java/xin/qishuo/child1/Calculate.java
内容如下

package xin.qishuo.child1;

public class Calculate {

    public static int add(int a, int b) {
        return a+b;
    }

}

2)创建 build.gradle 文件

vim ./child1/build.gradle

其内容如下:

plugins {
  id 'java'
}

repositories {
    mavenCentral()
}

dependencies {
    // Use JUnit Jupiter for testing. junit测试包
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
}

1.7. 子项目child2的配置

1)创建一个java类

vim ./child2/src/main/java/xin/qishuo/child2/CalculateService.java
内容如下

package xin.qishuo.child2;

import xin.qishuo.child1.Calculate; // 注意,这个是 child1 中的类

public class CalculateService {

    public static void main(String[] args) {
        int result = Calculate.add(1, 2);
        System.out.println(result);
    }

}

2)创建 build.gradle 文件

vim ./child2/build.gradle

其内容如下:

plugins {
  id 'java'
  id 'application'
}

repositories {
  mavenCentral()
}

application {
  mainClass = 'xin.qishuo.child2.CalculateService'
}

dependencies {
    // 声明 child2 对 child1 的依赖
    implementation project(':child1')
    // Use JUnit Jupiter for testing. junit测试包
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
}

1.8. 主项目 settings.gradle 配置

vim ./settings.gradle

其内容如下:

rootProject.name = 'multiModule'
include 'child1'
include 'child2'

1.9. 最终的目录结构如下

项目目录结构

.
├── build.gradle
├── child1
│   ├── build.gradle
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child1
│                           └── Calculate.java
├── child2
│   ├── build.gradle
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child2
│                           └── CalculateService.java
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

1.10. 查看任务以及执行run任务

./gradlew tasks --all
详细内容

[java@etdbmysql multiModule]$ ./gradlew tasks --all

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'multiModule'
------------------------------------------------------------

Application tasks
-----------------
child2:run - Runs this project as a JVM application

Build tasks
-----------
child1:assemble - Assembles the outputs of this project.
child2:assemble - Assembles the outputs of this project.
child1:build - Assembles and tests this project.
child2:build - Assembles and tests this project.
child1:buildDependents - Assembles and tests this project and all projects that depend on it.
child2:buildDependents - Assembles and tests this project and all projects that depend on it.
child1:buildNeeded - Assembles and tests this project and all projects it depends on.
child2:buildNeeded - Assembles and tests this project and all projects it depends on.
child1:classes - Assembles main classes.
child2:classes - Assembles main classes.
child1:clean - Deletes the build directory.
child2:clean - Deletes the build directory.
child1:jar - Assembles a jar archive containing the main classes.
child2:jar - Assembles a jar archive containing the main classes.
child1:testClasses - Assembles test classes.
child2:testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Distribution tasks
------------------
child2:assembleDist - Assembles the main distributions
child2:distTar - Bundles the project as a distribution.
child2:distZip - Bundles the project as a distribution.
child2:installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
child1:javadoc - Generates Javadoc API documentation for the main source code.
child2:javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'multiModule'.
child1:buildEnvironment - Displays all buildscript dependencies declared in project ':child1'.
child2:buildEnvironment - Displays all buildscript dependencies declared in project ':child2'.
dependencies - Displays all dependencies declared in root project 'multiModule'.
child1:dependencies - Displays all dependencies declared in project ':child1'.
child2:dependencies - Displays all dependencies declared in project ':child2'.
dependencyInsight - Displays the insight into a specific dependency in root project 'multiModule'.
child1:dependencyInsight - Displays the insight into a specific dependency in project ':child1'.
child2:dependencyInsight - Displays the insight into a specific dependency in project ':child2'.
help - Displays a help message.
child1:help - Displays a help message.
child2:help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
child1:javaToolchains - Displays the detected java toolchains.
child2:javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'multiModule'.
child1:outgoingVariants - Displays the outgoing variants of project ':child1'.
child2:outgoingVariants - Displays the outgoing variants of project ':child2'.
projects - Displays the sub-projects of root project 'multiModule'.
child1:projects - Displays the sub-projects of project ':child1'.
child2:projects - Displays the sub-projects of project ':child2'.
properties - Displays the properties of root project 'multiModule'.
child1:properties - Displays the properties of project ':child1'.
child2:properties - Displays the properties of project ':child2'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'multiModule'.
child1:resolvableConfigurations - Displays the configurations that can be resolved in project ':child1'.
child2:resolvableConfigurations - Displays the configurations that can be resolved in project ':child2'.
tasks - Displays the tasks runnable from root project 'multiModule' (some of the displayed tasks may belong to subprojects).
child1:tasks - Displays the tasks runnable from project ':child1'.
child2:tasks - Displays the tasks runnable from project ':child2'.

Verification tasks
------------------
child1:check - Runs all checks.
child2:check - Runs all checks.
child1:test - Runs the test suite.
child2:test - Runs the test suite.

Other tasks
-----------
child1:compileJava - Compiles main Java source.
child2:compileJava - Compiles main Java source.
child1:compileTestJava - Compiles test Java source.
child2:compileTestJava - Compiles test Java source.
components - Displays the components produced by root project 'multiModule'. [deprecated]
child1:components - Displays the components produced by project ':child1'. [deprecated]
child2:components - Displays the components produced by project ':child2'. [deprecated]
dependentComponents - Displays the dependent components of components in root project 'multiModule'. [deprecated]
child1:dependentComponents - Displays the dependent components of components in project ':child1'. [deprecated]
child2:dependentComponents - Displays the dependent components of components in project ':child2'. [deprecated]
model - Displays the configuration model of root project 'multiModule'. [deprecated]
child1:model - Displays the configuration model of project ':child1'. [deprecated]
child2:model - Displays the configuration model of project ':child2'. [deprecated]
prepareKotlinBuildScriptModel
child1:processResources - Processes main resources.
child2:processResources - Processes main resources.
child1:processTestResources - Processes test resources.
child2:processTestResources - Processes test resources.
child2:startScripts - Creates OS specific scripts to run the project as a JVM application.

BUILD SUCCESSFUL in 655ms
1 actionable task: 1 executed

./gradlew run

file

2. 示例2:集中配置子项目

使用示例1中 1.1. ~ 1.7 的配置,但是 child1 和 child2 中没有 build.gradle 文件。

2.1. 项目结构如下

项目目录结构

.
├── build.gradle
├── child1
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child1
│                           └── Calculate.java
├── child2
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child2
│                           └── CalculateService.java
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle

2.2. 根目录下的 settings.gradle 内容

rootProject.name = 'multiModule'
include 'child1'
include 'child2'

2.3. 根目录下的 build.gradle 内容

subprojects { // 给所有的子项目进行配置
  apply plugin: 'java'

  repositories {
    mavenCentral()
  }
}

// 配置 child1 子项目
project(":child1") {
  dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
  }
}

// 配置 child2 子项目
project(":child2") {
  apply plugin: 'application'

  dependencies {
     implementation project(':child1') // 声明对 child1 的依赖
     testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
  }

  application {
    mainClass = 'xin.qishuo.child2.CalculateService'
  }
}

2.4. 执行 gradlew build 与 gradlew run 命令

file

3. 示例3:同时配置子项目和根项目

使用示例1中 1.1. ~ 1.7 的配置,但是 child1 和 child2 中没有 build.gradle 文件。

3.1. 在根目录下增加了 src 目录,作为根项目的内容

mkdir -p ./src/main/java/xin/qishuo/

3.2. 在主项目中创建一个java类

vim ./src/main/java/xin/qishuo/Main.java
内容如下

package xin.qishuo;

import xin.qishuo.child1.Calculate; // 这是 child1 项目中的类

public class Main {

    public static void main(String[] args) {
        int result = Calculate.add(2, 2);
        System.out.println(result);
    }
}

3.3. 项目结构如下

项目目录结构

.
├── build.gradle
├── child1
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child1
│                           └── Calculate.java
├── child2
│   └── src
│       └── main
│           └── java
│               └── xin
│                   └── qishuo
│                       └── child2
│                           └── CalculateService.java
├── gradle
│   └── wrapper
│       ├── gradle-wrapper.jar
│       └── gradle-wrapper.properties
├── gradle.properties
├── gradlew
├── gradlew.bat
├── settings.gradle
└── src
    └── main
        └── java
            └── xin
                └── qishuo
                    └── Main.java

3.4. 主项目下的 settings.gradle 内容

rootProject.name = 'multiModule'
include 'child1'
include 'child2'

3.5. 主项目下的 build.gradle 内容

apply plugin: 'java'
apply plugin: 'application'

subprojects { // 给所有的子项目进行配置
  apply plugin: 'java'

  repositories {
    mavenCentral()
  }
}

// 配置 child1 子项目
project(":child1") {
  dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
  }
}

// 配置 child2 子项目
project(":child2") {
  apply plugin: 'application'

  dependencies {
     implementation project(':child1') // 声明对 child1 的依赖
     testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
  }

  application {
    mainClass = 'xin.qishuo.child2.CalculateService'
  }
}

// 配置根项目(rootProject)
dependencies {
  implementation project(':child1') // 声明对 child1 的依赖
  testImplementation 'org.junit.jupiter:junit-jupiter:5.9.1'
}

application {
    mainClass = 'xin.qishuo.Main'
}

3.6 运行 gradlew tasks 命令

./gradlew tasks --all
Task详细内容

> Task :tasks

------------------------------------------------------------
Tasks runnable from root project 'multiModule'
------------------------------------------------------------

Application tasks
-----------------
run - Runs this project as a JVM application
child2:run - Runs this project as a JVM application

Build tasks
-----------
assemble - Assembles the outputs of this project.
child1:assemble - Assembles the outputs of this project.
child2:assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
child1:build - Assembles and tests this project.
child2:build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
child1:buildDependents - Assembles and tests this project and all projects that depend on it.
child2:buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
child1:buildNeeded - Assembles and tests this project and all projects it depends on.
child2:buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
child1:classes - Assembles main classes.
child2:classes - Assembles main classes.
clean - Deletes the build directory.
child1:clean - Deletes the build directory.
child2:clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
child1:jar - Assembles a jar archive containing the main classes.
child2:jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.
child1:testClasses - Assembles test classes.
child2:testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Distribution tasks
------------------
assembleDist - Assembles the main distributions
child2:assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
child2:distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
child2:distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.
child2:installDist - Installs the project as a distribution as-is.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.
child1:javadoc - Generates Javadoc API documentation for the main source code.
child2:javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'multiModule'.
child1:buildEnvironment - Displays all buildscript dependencies declared in project ':child1'.
child2:buildEnvironment - Displays all buildscript dependencies declared in project ':child2'.
dependencies - Displays all dependencies declared in root project 'multiModule'.
child1:dependencies - Displays all dependencies declared in project ':child1'.
child2:dependencies - Displays all dependencies declared in project ':child2'.
dependencyInsight - Displays the insight into a specific dependency in root project 'multiModule'.
child1:dependencyInsight - Displays the insight into a specific dependency in project ':child1'.
child2:dependencyInsight - Displays the insight into a specific dependency in project ':child2'.
help - Displays a help message.
child1:help - Displays a help message.
child2:help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
child1:javaToolchains - Displays the detected java toolchains.
child2:javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'multiModule'.
child1:outgoingVariants - Displays the outgoing variants of project ':child1'.
child2:outgoingVariants - Displays the outgoing variants of project ':child2'.
projects - Displays the sub-projects of root project 'multiModule'.
child1:projects - Displays the sub-projects of project ':child1'.
child2:projects - Displays the sub-projects of project ':child2'.
properties - Displays the properties of root project 'multiModule'.
child1:properties - Displays the properties of project ':child1'.
child2:properties - Displays the properties of project ':child2'.
resolvableConfigurations - Displays the configurations that can be resolved in root project 'multiModule'.
child1:resolvableConfigurations - Displays the configurations that can be resolved in project ':child1'.
child2:resolvableConfigurations - Displays the configurations that can be resolved in project ':child2'.
tasks - Displays the tasks runnable from root project 'multiModule' (some of the displayed tasks may belong to subprojects).
child1:tasks - Displays the tasks runnable from project ':child1'.
child2:tasks - Displays the tasks runnable from project ':child2'.

Verification tasks
------------------
check - Runs all checks.
child1:check - Runs all checks.
child2:check - Runs all checks.
test - Runs the test suite.
child1:test - Runs the test suite.
child2:test - Runs the test suite.

Other tasks
-----------
compileJava - Compiles main Java source.
child1:compileJava - Compiles main Java source.
child2:compileJava - Compiles main Java source.
compileTestJava - Compiles test Java source.
child1:compileTestJava - Compiles test Java source.
child2:compileTestJava - Compiles test Java source.
components - Displays the components produced by root project 'multiModule'. [deprecated]
child1:components - Displays the components produced by project ':child1'. [deprecated]
child2:components - Displays the components produced by project ':child2'. [deprecated]
dependentComponents - Displays the dependent components of components in root project 'multiModule'. [deprecated]
child1:dependentComponents - Displays the dependent components of components in project ':child1'. [deprecated]
child2:dependentComponents - Displays the dependent components of components in project ':child2'. [deprecated]
model - Displays the configuration model of root project 'multiModule'. [deprecated]
child1:model - Displays the configuration model of project ':child1'. [deprecated]
child2:model - Displays the configuration model of project ':child2'. [deprecated]
prepareKotlinBuildScriptModel
processResources - Processes main resources.
child1:processResources - Processes main resources.
child2:processResources - Processes main resources.
processTestResources - Processes test resources.
child1:processTestResources - Processes test resources.
child2:processTestResources - Processes test resources.
startScripts - Creates OS specific scripts to run the project as a JVM application.
child2:startScripts - Creates OS specific scripts to run the project as a JVM application.

Rules
-----
Pattern: clean《TaskName》: Cleans the output files of a task.
Pattern: build《ConfigurationName》: Assembles the artifacts of a configuration.

BUILD SUCCESSFUL in 716ms
1 actionable task: 1 executed

3.7. 执行 gradlew build 与 gradlew run 命令

file

附录

附录A. 相关联的文章

附录B. 参考

Gradle: 创建含有多模块(即多个子项目)的项目:
https://www.letianbiji.com/gradle/gradle-sub-projects.html