Gradle中的buildScript代码块

2017-02-03  本文已影响0人  LoWang

在编写Gradle脚本的时候,在build.gradle文件中经常看到这样的代码:

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在执行脚本时,会优先执行buildscript代码块中的内容,然后才会执行剩余的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声明说明了在执行其余的build脚本时,class loader可以使用这些你提供的依赖项。这也正是我们使用buildscript代码块的目的。

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)
        }

    }
}
上一篇 下一篇

猜你喜欢

热点阅读