1 前言
Gradle由于构建速度比Maven快,且比Maven灵活,虽然现在有了mvnd,但是构建速度还是远比不上Gradle。因此一些大型项目使用Gradle进行构建能够节省很多的构建时间。但一个问题是Gradle的多模块嵌套项目比较难构建。本文就带着大家一起实践一下。
2 环境
Gradle 7.3.3Spring Boot 2.6.3
3 开始构建项目
3.1 创建项目
file>new project 选中Gradle Java 下一步(next)
输入项目信息 完成(Finish)
然后右键根模块New -> Module依次创建子模块 api common 等
3.2 修改root build.gradle
plugins {
id 'java'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'org.springframework.boot' version '2.6.3'
}
ext {
set('springCloudAlibabaVersion', "2021.1")
set('springCloudVersion', "2021.0.0")
}
allprojects {
apply plugin: 'java'
group 'com.f'
version '1.0.0'
// 设置编译和运行的jre兼容版本
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
maven {
url 'https://repo.huaweicloud.com/repository/maven/'
}
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.8.2'
}
test {
useJUnitPlatform()
}
}
// 应用于所有依赖的子项目
subprojects {
// 应用插件
apply plugin: "org.springframework.boot"
apply plugin: "io.spring.dependency-management"
// spring boot构建任务
springBoot {
buildInfo()
}
dependencyManagement {
// 导入maven依赖管理的bom
imports {
mavenBom 'org.apache.commons:commons-lang3:3.12.0'
mavenBom "com.alibaba.cloud:spring-cloud-alibaba-dependencies:${springCloudAlibabaVersion}"
mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
}
}
/**
* 为所有模块指定公共的依赖
* 注意这里有些默认不用再指定版本了,已经由上面的dependencyManagement管理了
*/
dependencies {
annotationProcessor "org.springframework.boot:spring-boot-configuration-processor"
annotationProcessor "org.projectlombok:lombok"
compileOnly "org.springframework.boot:spring-boot-configuration-processor"
compileOnly "org.projectlombok:lombok"
testAnnotationProcessor "org.projectlombok:lombok"
testCompileOnly "org.projectlombok:lombok"
testImplementation "org.springframework.boot:spring-boot-starter-test"
}
}
4 创建嵌套模块
右键common,service聚合模块 New -> Module 创建下级模块父级模块还是root,但是目录需要指定为聚合模块下的子目录
5 结果
settings.gradle
rootProject.name = 'f-cloud'
include 'api'
include 'common'
include 'service'
include 'gateway'
include 'common:common-core'
findProject(':common:common-core')?.name = 'common-core'
include 'common:common-cache'
findProject(':common:common-cache')?.name = 'common-cache'
include 'common:common-service'
findProject(':common:common-service')?.name = 'common-service'
include 'common:common-web'
findProject(':common:common-web')?.name = 'common-web'
include 'service:file-service'
findProject(':service:file-service')?.name = 'file-service'
include 'service:message-service'
findProject(':service:message-service')?.name = 'message-service'
include 'service:order-service'
findProject(':service:order-service')?.name = 'order-service'
include 'service:pay-service'
findProject(':service:pay-service')?.name = 'pay-service'
include 'service:sys-service'
findProject(':service:sys-service')?.name = 'sys-service'