多模块项目

返回构建工具


概念

将一个大型项目拆分为多个子模块,各模块独立编译、测试、打包,同时共享父项目的依赖版本和构建配置。

典型模块划分

my-project/
├── my-api/        # 接口定义、DTO
├── my-core/       # 核心业务逻辑
├── my-web/        # Web 层(依赖 core)
└── my-app/        # 启动模块(依赖 web)

Maven 多模块

查看 Maven 详细文档

目录结构

parent/
├── pom.xml              ← packaging = pom
├── module-a/
│   └── pom.xml
└── module-b/
    └── pom.xml

父 pom.xml

<groupId>com.example</groupId>
<artifactId>parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
 
<modules>
    <module>module-a</module>
    <module>module-b</module>
</modules>
 
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.2.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

子模块 pom.xml

<parent>
    <groupId>com.example</groupId>
    <artifactId>parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
</parent>
 
<artifactId>module-a</artifactId>
 
<!-- 子模块间依赖 -->
<dependencies>
    <dependency>
        <groupId>com.example</groupId>
        <artifactId>module-b</artifactId>
        <version>${project.version}</version>
    </dependency>
</dependencies>

常用命令

mvn install                  # 构建所有模块
mvn install -pl module-a     # 只构建指定模块
mvn install -pl module-a -am # 同时构建其依赖的模块

Gradle 多模块

查看 Gradle 详细文档

settings.gradle.kts

rootProject.name = "my-project"
 
include(
    "module-a",
    "module-b",
    "module-web"
)

根 build.gradle.kts(共享配置)

subprojects {
    apply(plugin = "java")
 
    repositories { mavenCentral() }
 
    dependencies {
        testImplementation("org.junit.jupiter:junit-jupiter:5.10.0")
    }
}

子模块间依赖

// module-web/build.gradle.kts
dependencies {
    implementation(project(":module-a"))
    implementation(project(":module-b"))
}

常用命令

./gradlew build                     # 构建所有模块
./gradlew :module-a:build           # 只构建指定模块
./gradlew :module-web:dependencies  # 查看模块依赖树

相关文档