一个项目即包括服务器端又包括客户端,二者放在一起管理比较方便,这时就可以使用多工程构建。即一个父工程下面包含相关的若干子工程。
创建多工程可以有2种方式:
手工创建子工程(文件夹)
或借助IDE工具自动化创建
比如在IntelliJ中,可以右键父工程,New, Module
这个Module就是一个子项目
Gradle多项目有如下特征
在父工程根目录下存在一个'settings.gradle'文件(官网settings.gradle, build.gradle相关说明)
A settings.gradle file in the root or master directory of the project
• A build.gradle file in the root or master directory
• Child directories that have their own *.gradle build files (some multi-project builds may omit child project build scripts)
The settings.gradle file tells Gradle how the project and subprojects are structured.
By default, Gradle uses the name of the directory in which it finds the settings.gradle as the name of the root project.
Each project will usually have its own build file, but that’s not necessarily the case. In the above example, the services project is just a container or grouping of other subprojects. There is no build file in the corresponding directory.
The root build.gradle is often used to share common configuration between the child projects, for example by applying the same sets of plugins and dependencies to all the child projects. It can also be used to configure individual subprojects when it is preferable to have all the configuration in
one place.
Another thing to bear in mind is that the build files might not be called build.gradle. Many projects will name the build files after the subproject names, such as api.gradle and services.gradle from the previous example. Such an approach helps a lot in IDEs because it’s tough to work out which
build.gradle file out of twenty possibilities is the one you want to open. This little piece of magic is handled by the settings.gradle file, but as a build user you don’t need to know the details of how it’s done. Just have a look through the child project directories to find the files with the .gradle suffix.
举例如下:
父工程:mail-ddns: build.gradle
3个子工程:
mdCommon: mdCommon.gradle
mdServer: mdServer.gradle
mdClient: mdClient.gradle
//以下为settings.gradle代码, 作用是让gradle知道子模块的存在
//===settings.gradle===
rootProject.name = 'mail-ddns' // 工程名
include 'mdCommon'
include 'mdServer'
include 'mdClient'
/**
* rename subproject build.gradle
* 将子工程原来的 build.gradle改名(使用 子工程名.grdle)
*/
rootProject.children.each{
it.buildFileName = it.name + '.gradle'
}
主工程build.gradle, 配置公共部分即可(共用的依赖, 插件等)
//----root: build.gradle----
// 一般来说工程依赖的类都需要在打jar包时将其复制到包中, 这项功能需要shadow插件的支持, 加入以下代码:
plugins {
id 'com.github.johnrengelman.shadow' version '7.1.2'
id 'java'
}
allprojects {
repositories {
mavenLocal()
}
}
dependencies {
implementation 'ch.qos.logback:logback-classic:1.2.11'
//...
}
mdServer 和 mdClient共同使用的类放在mdCommon中
dependencies {
implementation project(':mdCommon')
}
// 这保证编译mdServer 和 mdClient之前,会先编译mdCommon
当子工程与主工程version不同时, 以子工程为准.