在編寫Gradle腳本的時候饲化,在build.gradle文件中經(jīng)车敉看到這樣的代碼:
build.gradle
buildscript {
ext {
dependencyManagementPluginVersion = '0.6.0.RELEASE'
springBootVersion = '1.4.3.RELEASE'
}
repositories {
maven { url 'http://maven.aliyun.com/nexus/content/groups/public'}
jcenter()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath "io.spring.gradle:dependency-management-plugin:${dependencyManagementPluginVersion}"
classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
classpath "net.researchgate:gradle-release:2.4.0"
}
} mavenCentral()
}
buildscript中的聲明是gradle腳本自身需要使用的資源杂抽。可以聲明的資源包括依賴項寂呛、第三方插件坯汤、maven倉庫地址等。而在build.gradle文件中直接聲明的依賴項善延、倉庫地址等信息是項目自身需要的資源少态。gradle在執(zhí)行腳本時,會優(yōu)先執(zhí)行buildscript代碼塊中的內(nèi)容易遣,然后才會執(zhí)行剩余的build腳本
gradle是由groovy語言編寫的彼妻,支持groovy語法,可以靈活的使用已有的各種ant插件、基于jvm的類庫侨歉,這也是它比maven屋摇、ant等構(gòu)建腳本強(qiáng)大的原因。雖然gradle支持開箱即用幽邓,但是如果你想在腳本中使用一些第三方的插件炮温、類庫等,就需要自己手動添加對這些插件牵舵、類庫的引用柒啤。而這些插件、類庫又不是直接服務(wù)于項目的畸颅,而是支持其它build腳本的運(yùn)行担巩。所以你應(yīng)當(dāng)將這部分的引用放置在buildscript代碼塊中。gradle在執(zhí)行腳本時没炒,會優(yōu)先執(zhí)行buildscript代碼塊中的內(nèi)容涛癌,然后才會執(zhí)行剩余的build腳本。
舉個例子窥浪,假設(shè)我們要編寫一個task祖很,用于解析csv文件并輸出其內(nèi)容。雖然我們可以使用gradle編寫解析csv文件的代碼漾脂,但其實apache有個庫已經(jīng)實現(xiàn)了一個解析csv文件的庫供我們直接使用假颇。我們?nèi)绻胍褂眠@個庫,需要在gradle.build文件中加入對該庫的引用骨稿。
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.apache.commons:commons-csv:1.0'
}
}
import org.apache.commons.csv.*
task printCSV() {
doLast {
def records = CSVFormat.EXCEL.parse(new FileReader('config/sample.csv'))
for (item in records) {
print item.get(0) + ' '
println item.get(1)
}
}
}
buildscript代碼塊中的repositories和dependencies的使用方式與直接在build.gradle文件中的使用方式幾乎完全一樣笨鸡。唯一不同之處是在buildscript代碼塊中你可以對dependencies使用classpath聲明。該classpath聲明說明了在執(zhí)行其余的build腳本時坦冠,class loader可以使用這些你提供的依賴項形耗。這也正是我們使用buildscript代碼塊的目的。
- 如果你的項目中需要使用該類庫的話辙浑,就需要定義在buildscript代碼塊之外的dependencies代碼塊中激涤。所以有可能會看到在build.gradle中出現(xiàn)以下代碼:
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
compile 'org.springframework.ws:spring-ws-core:2.2.0.RELEASE',
'org.apache.commons:commons-csv:1.0'
}
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'org.apache.commons:commons-csv:1.0'
}
}
import org.apache.commons.csv.*
task printCSV() {
doLast {
def records = CSVFormat.EXCEL.parse(new FileReader('config/sample.csv'))
for (item in records) {
print item.get(0) + ' '
println item.get(1)
}
}
}