一般中大型項目都會將程序分為多個模塊來開發,除了依賴第三方庫之外,不同模塊之間彼此也可能存在依賴關系, Gradle 提供的配置方式,可以很容易的完成多模塊建構。
假設現在有一個項目,區分為核心模塊,前端及管理系統兩個 web 模塊,兩個 web 模塊除了基於 Spring MVC 框架之外,也都依賴核心模塊提供的服務。
首先建立工程資料夾 gradle_modules,並且在工程資料夾下針對三個模塊個別建立資料夾,接着執行初始化指令
mkdir gradle_modules
mkdir gradle_modules\core
mkdir gradle_modules\front_web
mkdir gradle_modules\admin_web
cd gradle_modules
gradle init
接着修改 settings.gradle 文件,將三個模塊加入其中
rootProject.name = 'gradle_modules'
include 'core', 'front_web', 'admin_web'
寫代碼的時候通常會考慮到代碼重用的問題, Gradle 建構腳本也有類似的功能, allprojects 屬性塊可以設定所有模塊共享的配置,例如:所有模塊都引入 idea 插件
allprojects {
apply plugin: 'idea'
}
subprojects 屬性塊可以設定所有子模塊共享的配置,例如:所有模塊都引入 java 插件, repositories,依賴包,依賴包版本等
subprojects {
apply plugin: 'java'
repositories {
jcenter()
}
ext {
slf4jVersion = '1.7.21'
springVersion = '4.3.6.RELEASE'
hibernateVersion ='5.0.6.Final'
}
dependencies {
compile(
"org.slf4j:slf4j-api:${slf4jVersion}"
)
}
configurations {
all*.exclude group: 'commons-logging'
}
}
還可以在 configure 屬性塊根據模塊名稱引入特定插件
configure(subprojects.findAll {it.name.contains('web')}) {
apply plugin: 'war'
}
個別模塊所需要的配置則可以在 project 屬性塊中設定
project(':core') {
dependencies {
compile(
"org.springframework:spring-context:$springVersion",
"org.springframework:spring-orm:$springVersion",
"org.springframework:spring-tx:$springVersion",
"org.springframework.data:spring-data-jpa:1.10.3.RELEASE",
"org.hibernate:hibernate-entitymanager:$hibernateVersion",
"c3p0:c3p0:0.9.1.2",
"mysql:mysql-connector-java:6.0.4"
)
}
}
project(':front_web') {
dependencies {
compile(
project (':core'),
"org.springframework:spring-web:${springVersion}"
)
}
}
project(':admin_web') {
dependencies {
compile(
project (':core'),
"org.springframework:spring-web:${springVersion}"
)
}
}
以上是其中一種方式,將所有內容寫在工程資料夾下的 build.gradle 中,如果是大型項目,切分為眾多模塊,且建構腳本的內容既多且復雜,那也可以將每個模塊資料夾下產生一份 build.gradle,用來處理個別模塊的建構過程,類似父類別與子類別的概念,將需要重用的屬性塊及函數等寫在上層 build.gradle 中,即可讓所有模塊的 build.gradle 調用
以上是本文對多模塊做法的介紹,可以由此下載 相關文件