Gradle


#Gradle

初始Gradle

推荐资料:https://lippiouyang.gitbooks.io/gradle-in-action-cn/content/gradle/using-command-line.html

1.Gradle基本命令

1.安装Gradle

下载:https://gradle.org/releases/
配置Gradle环境变量GRADLE_HOME,并添加到path路径下
在命令行执行gradle -v

$ gradle -v

------------------------------------------------------------
Gradle 5.0
------------------------------------------------------------

Build time:   2018-11-26 11:48:43 UTC
Revision:     7fc6e5abf2fc5fe0824aec8a0f5462664dbcd987

Kotlin DSL:   1.0.4
Kotlin:       1.3.10
Groovy:       2.5.4
Ant:          Apache Ant(TM) version 1.9.13 compiled on July 10 2018
JVM:          1.8.0_181 (Oracle Corporation 25.181-b13)
OS:           Windows 10 10.0 amd64

执行gradle命令时,Gradle会去查找build.gradle的文件,如果找不到会显示帮助信息。

$ gradle

> Task :help

Welcome to Gradle 5.0.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

For troubleshooting, visit https://help.gradle.org

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
2.HelloWorld

编写一个build.gradle文件,并输入以下内容:

task helloWorld {
	doLast {
		println 'Hello world'
	}
}

task定义一个任务,即helloWorld就是一个任务,doLast是这个任务的一个动作(action)!
执行命令:gradle -q helloWorld

$ gradle -q helloWorld
Hello world

对于参数-q:

-q, --quiet               Log errors only.

更多参数可执行gradle --help查看

3.查看任务

通过命令gradle tasks可以查看任务:

$ gradle -q tasks --all

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'demo01_hello_world'.
components - Displays the components produced by root project 'demo01_hello_world'. [incubating]
dependencies - Displays all dependencies declared in root project 'demo01_hello_world'.
dependencyInsight - Displays the insight into a specific dependency in root project 'demo01_hello_world'.
dependentComponents - Displays the dependent components of components in root project 'demo01_hello_world'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'demo01_hello_world'. [incubating]
projects - Displays the sub-projects of root project 'demo01_hello_world'.
properties - Displays the properties of root project 'demo01_hello_world'.
tasks - Displays the tasks runnable from root project 'demo01_hello_world'.

Other tasks
-----------
groupTherapy
startSession
yayGradle0
yayGradle1
yayGradle2

Build Setup tasksHelp tasksOther tasks都是任务组。

4.排除任务 -x

排除的任务不会被执行

$ gradle groupTherapy -x startSession

> Task :yayGradle0
Gradle rocks

> Task :yayGradle1
Gradle rocks

> Task :yayGradle2
Gradle rocks

BUILD SUCCESSFUL in 0s
3 actionable tasks: 3 executed
5.驼峰命名缩写执行

groupTherapy的缩写是gT。
不能有多个任务有同样的缩写,否则gradle不知道到底只得是哪个任务。

$ gradle gT

> Task :startSession
[ant:echo] Repeat after me

> Task :yayGradle0
Gradle rocks

> Task :yayGradle1
Gradle rocks

> Task :yayGradle2
Gradle rocks

BUILD SUCCESSFUL in 0s
4 actionable tasks: 4 executed

2.Gradle守护进程

守护进程以后台进程方式进行Gradle。
第一次执行Gradle命令,会启动守护进程。

$ gradle gT
To honour the JVM settings for this build a new JVM will be forked. Please consider using the daemon: https://docs.gradle.org/5.0/userguide/gradle_daemon.html.
# 启动Daemon
> Starting Daemon
省略...

之后执行的命令就不会有Starting Daemon,而是直接通过守护进程执行命令(因为守护进程已经启动了)
停止gradle守护进程 --stop:

$ gradle --stop
Stopping Daemon(s)
1 Daemon stopped

这样gradle的守护进程就停止了。
如果不想使用Gradle守护进程可以使用 --no-daemon,这样每次都会启动gradle:

$ gradle gT --no-daemon

3.项目中使用Gradle

基本配置

在build.gradle中,引入java插件:
java插件提供了将.java文件编译成.class文件和打包.jar包文件的功能。java插件默认约定源文件目录为src/main/java

apply plugin: 'java'

设置java编译环境:

sourceCompatibility = 1.6

设置项目版本

version = 0.1

设置源码目录(默认在src/main/java):

sourceSets {
    main {
        java {
            srcDirs = ['src/demo']
        }
    }
}

设置manifest相关信息:

jar {
    manifest {
        attributes 'Main-class': 'com.gradle.demo.App'
    }
}
配置依赖
定义仓库

配置访问mavenCentral库:

repositories {
    mavenCentral()
}

配置添加jar包依赖:

dependencies {
	// 方式一 gourp: '', name: '', version: ''
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.1'
    // 方式二 'group:name:version'
    compile 'junit:junit:4.12'
}

compile 表示引入的这个jar包是在编译源代码和运行时要使用的

使用war插件

war 插件约定项目打包方式为war包,并且约定web资源文件放在src/main/webapp目录下。

// war插件 使项目打包为war包
apply plugin: 'war'

providedCompile : 编译时需要,运行时不需要,由环境提供
runtime: 编译时不需要,运行时需要

dependencies {
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.1'
    compile 'junit:junit:4.12'
    providedCompile 'javax.servlet:servlet-api:2.5'
    runtime 'javax.servlet:jstl:1.1.2'
}

定制web项目相关信息:

webAppDirName = 'webfiles'

war {
    from 'static'
}

webAppDirName 指定webapp的名字(如果不使用默认的webapp作为名字)
from 指定静态资源目录,比如html,css,js的存放路径,根目录还是webAppDirName 指定的目录

4.多个plugin的定义

plugins {
    id 'java'
    id 'war'
    id "org.akhikhl.gretty" version "2.0.0"
}

5.Gradle Wrapper包装器

执行gradle wrapper,可以生成一个Gradle包装器,他的作用是构建一个与执行gradle wrapper时同样的gradle环境。执行后会生成gradlew(*nix环境)、gradlew.bat(windows环境)文件,以及gradle文件夹。
在一个没有Gradle的环境中要执行Gradle命令时直接可以使用gradlewgradlew.bat来运行即可,首次运行:

$ gradlew.bat build
# 回去下载对应的Gradle
Downloading https://services.gradle.org/distributions/gradle-5.0-bin.zip
.................................................................................

BUILD SUCCESSFUL in 12s

默认包装器是和生成这个包装器的Gradle是同一个版本。也可以定制包装器信息:

task setWrapper(type: Wrapper) {
    gradleVersion = '1.2'
}

执行gradle setWrapper,就会生成相应的信息。即gradlew.bat这个版本是使用的1.2了。
配置wrapper下载位置和解压位置:

task setWrapper(type: Wrapper) {
    gradleVersion = '1.7'
    distributionPath = 'www.xxx.html'
    distributionPath = 'gradle-dist'
}

配置文件下载下来后解压位置 用户家目录.gradle\,比如上面配置的wrapper是1.7版本的,从www.xxx.html下载下来,解压后目录在用户家目录.gradle\gradle-dist\文件夹下。

6.配置

就像maven的pom.xml文件,Gradle通过build.gradle配置。Gradle会通过build.gradle配置初始化一个org.gradle.api.Project变量,这个实例变量可访问下面这些方法:
在这里插入图片描述
build.gradle配置:

apply plugin: 'java'

task setWrapper(type: Wrapper) {
    gradleVersion = '1.7'
    distributionPath = 'www.xxx.html'
    distributionPath = 'gradle-dist'
}

setDescription("myproject")
setVersion("v1.01")

println "description of project $name -> " + project.description +" -> " + project.version  + "/$version"

执行命令:

$ gradle -q build
description of project demo02 -> myproject -> v1.01/v1.01

构建task任务属性:
在这里插入图片描述

扩展属性

可以通过ext扩展属性:

project.ext.mykey = 12

ext {
    mykey1 = 13
    mykey2 = 14
}

println project.mykey
println project.mykey1
println project.mykey2

一、任务task

1.新建一个task

在build.gradle文件中新建一个任务:

task hello {
    doLast {
        println "hello world!"
    }
}

或者:

task hello {
    println "hello world!"
}

在控制台执行gradle hello命令

F:\workspace\demo>gradle hello

> Task :hello
hello world!

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

或都执行gradle -q hello命令,-q. 代表 quite 模式. 它不会生成 Gradle 的日志信息 (log messages), 所以用户只能看到 tasks 的输出

F:\workspace\groovy-demo>gradle -q hello
hello world!
多任务依赖
// 定义一个任务startSession ,任务中调用chant方法
task startSession {
	doLast {
		chant()
	}
}
// 定义chant方法
def chant() {
	// 继承ant
	ant.echo(message: 'Repeat after me')
}
// 动态定义3个任务yayGradle0,yayGradle1,yayGradle2
3.times {
	// $it隐式变量,获取遍历次数
	task "yayGradle$it" {
		doLast {
			println 'Gradle rocks'
		}
	}
}
// yayGradle0依赖任务startSession
yayGradle0.dependsOn startSession

// yayGradle2依赖yayGradle1,和yayGradle0
yayGradle2.dependsOn yayGradle1, yayGradle0

// 任务groupTherapy依赖yayGradle2
task groupTherapy(dependsOn: yayGradle2)

运行命令 gradle groupTherapy执行任务groupTherapy,会依据依赖关系执行任务:

$ gradle groupTherapy

> Task :startSession
[ant:echo] Repeat after me

> Task :yayGradle0
Gradle rocks

> Task :yayGradle1
Gradle rocks

> Task :yayGradle2
Gradle rocks

2.任务依赖一

新建一个任务 A

task A{
	doLast {
		println "我是任务A"
	}
}

新建一个任务 B

task B{
	doLast {
		println "我是任务B"
	}
}

修改任务B依赖任务parent

task B(dependsOn: A) {
	doLast {
		println "我是任务B"
	}
}

任务A一定要在任务B之前定义,在控制台执行gradle -q B:

F:\workspace\groovy-demo>gradle -q B
我是任务A
我是任务B

由于B任务依赖A任务,所以在执行B任务之前会先执行任务A。

3.任务依赖二

前面的依赖是建立在被依赖的任务已经存在的情况下的,下面的依赖是一个任务依赖一个还未定义的任务。
新建一个一个任务taskA,使用task依赖任务taskB:

task taskA(dependsOn: 'taskB') {
	doLast {
		println "我是任务taskA"
	}
}

新建一个任务taskB

task taskB {
	doLast {
		println "我是任务taskB"
	}
}

在控制台执行gradle -q taskA:

F:\workspace\groovy-demo>gradle -q taskA
我是任务taskB
我是任务taskA

4.创建动态任务

gradle中可以创建动态任务:

4.times { count ->
	task "task$count" {
		doLast {
			println "任务$count"
		}
	}
}

上面动态建立了4个任务,分别是task0-task3,在控制台执行:

F:\workspace\groovy-demo>gradle -q task3
任务3

5.声明任务后添加依赖

可以通过 .dependsOn 为任务添加依赖:

4.times { count ->
    task "task$count" {
        doLast {
            println "任务$count"
        }
    }
}
// 添加依赖
task0.dependsOn task1,task2

6.任务执行的动作

可以给任务指定动作:

task task0 {
    println  "hello inner"
    doFirst {
        println "doFirst inner"
    }
    doLast {
        println "doLast inner"
    }
}
task0 {
    println 'hello outer'
}
task0.doLast {
    println "edit doLast outer"
}

task0.doLast {
    println "edit doLast outer"
}

执行任务task0,在控制台输出:

F:\workspace\groovy-demo>gradle -q  task0
hello inner
hello outer
doFirst inner
doLast inner
edit doLast outer
edit doLast outer

任务的每个动作都可以被修改(添加)的,每一次动作的操作都会被执行。doFirst 和 doLast 可以被执行许多次. 他们分别可以在任务动作列表的开始和结束加入动作。

7.任务属性

可以在当前动作中获取当前任务,通过**$任务名的方式来获取,每个任务还有自定义属性name**来获取当前任务的名字:

task hello {
    println "hello world!"
}

hello.doFirst {
    println "我是任务$hello.name"
}

在控制台打印:

F:\workspace\groovy-demo>gradle -q hello
hello world!
我是任务hello
自定义属性

可以为任务自定义属性:

task hello {
    ext.age = 10
}

hello.doFirst {
	// 获取属性中的值
    println "任务${hello.name}的属性age的值是${hello.age}"
}

task hi(dependsOn: hello) {
	// 获取属性中的值
    println  "${hello.name}的age属性是age是${hello.age}"
}

控制台输出:

F:\workspace\groovy-demo>gradle -q hi
hello的age属性是age是10
任务hello的属性age的值是10
根据任务的不同输出不同的值
task hello {
    // 这里不受影响
    println "版本是$version"
    doFirst {
        // 这里受下面修改的影响
        println "doFirst -> 版本是$version"
    }
}
gradle.taskGraph.whenReady {taskGraph ->
    // 如果包含hello任务
    if (taskGraph.hasTask(hello)) {
        version = 'V2.0'
    } else {
        version = 'V1.0'
    }
}

控制台输出:

F:\workspace\groovy-demo>gradle -q hello
版本是1.0-SNAPSHOT
doFirst -> 版本是V2.0

二、Java构建

使用Java插件

apply plugin: 'java'

或者:

plugins {
    id 'java'
}

命令

build:构建
assemble:编译并打包代码, 但是不运行单元测试
check:编译并测试代码
clean:删除构建生成的文件

引入仓库

在repositories中可以设置要使用的仓库的位置。
引入maven仓库:

repositories {
    mavenCentral()
}

或者:

repositories {
    maven {
        url "http://repo.mycompany.com/maven2"
    }
}

使用ivy仓库:

repositories {
    ivy {
        url "http://repo.mycompany.com/repo"
    }
}

一个项目可以有好几个库. Gradle 会根据依赖定义的顺序在各个库里寻找它们, 在第一个库里找到了就不会再在第二个库里找它了.

添加依赖

可以在dependencies中加入要引用的依赖,group/name/version唯一确定一个依赖。compile表示编译阶段,testCompile表示测试编译阶段

compile:用来编译项目源代码的依赖.
runtime:在运行时被生成的类使用的依赖. 默认的, 也包含了编译时的依赖.
testCompile:编译测试代码的依赖. 默认的, 包含生成的类运行所需的依赖和编译源代码的依赖.
testRuntime:运行测试所需要的依赖. 默认的, 包含上面三个依赖.
dependencies {
    compile 'commons-collections:commons-collections:3.2'
    testCompile 'junit:junit:4.+'
}

依赖信息简写

dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

设置JDK版本和项目打包版本

sourceCompatibility = 1.8
version = 'v1.0'

任务

所有任务都是org.gradle.api.DefaultTask类型,是 org.gradle.api.Task 的实现。Default所有属性都是私有的,只能通过getter和setter来访问。但是groovy允许通过名字访问。
添加额外属性:

version = '0.1-SNAPSHOT'
// 定义好一个任务
task printVersion {
    doFirst {
        println "Version >> $version"
    }
    doLast {
        println "Version $version"
    }
}
// 为这个任务添加额外的任务
printVersion.doFirst { println "hello"}
printVersion.doLast { println 'bye'}

访问任务属性

日志:task默认提供多个级别的日志打印功能

task printVersion {
    doFirst {
        println "Version >> $version"
    }
    doLast {
        logger.quiet " 这是日志打印!!"
        logger.debug '这是debug级别的日志'
    }
}

task的group和description属性:group表示任务的分组,description表示任务的描述

task printVersion {

    group = '任务分组'
    description = '任务描述'

    doFirst {
        println "Version >> $version"
    }
    doLast {
        logger.quiet " 这是日志打印!!"
        logger.debug '这是debug级别的日志'
    }
}

执行gradle tasks查看任务:

$ gradle tasks

> Task :tasks

------------------------------------------------------------
All tasks runnable from root project
------------------------------------------------------------

Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
buildDependents - Assembles and tests this project and all projects that depend on it.
buildNeeded - Assembles and tests this project and all projects it depends on.
classes - Assembles main classes.
clean - Deletes the build directory.
jar - Assembles a jar archive containing the main classes.
testClasses - Assembles test classes.

Build Setup tasks
-----------------
init - Initializes a new Gradle build.
wrapper - Generates Gradle wrapper files.

Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.

Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'demo01'.
components - Displays the components produced by root project 'demo01'. [incubating]
dependencies - Displays all dependencies declared in root project 'demo01'.
dependencyInsight - Displays the insight into a specific dependency in root project 'demo01'.
dependentComponents - Displays the dependent components of components in root project 'demo01'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'demo01'. [incubating]
projects - Displays the sub-projects of root project 'demo01'.
properties - Displays the properties of root project 'demo01'.
tasks - Displays the tasks runnable from root project 'demo01'.

Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.

任务分组 tasks
----------
printVersion - 任务描述

Rules
-----
Pattern: clean<TaskName>: Cleans the output files of a task.
Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.
Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a configuration.

To see all tasks and more detail, run gradle tasks --all

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
定义任务依赖
task first  {
    doFirst {
        println 'first'
    }
}

task second {
    doLast {
        println 'second'
    }
}

task third (dependsOn: [first, second]) {
    doLast {
        println 'third'
    }
}

task four {
    doLast {
        println 'four'
    }
}

// 依赖多个任务用,号隔开
//four.dependsOn third
four.dependsOn(third)
指定任务结束后执行的任务

如下,定义了两个任务,通过最后的second.finalizedBy指定second任务执行后执行first任务。

task first  {
    doFirst {
        println 'first'
    }
}

task second {
    doLast {
        println 'second'
    }
}

second.finalizedBy first

使用类自定义属性
version = new ProjectVersion(1, 2, false)

class ProjectVersion {
    // groovy 中会为属性自动添加getter/setter方法
    Integer major
    Integer minor
    Boolean release

    ProjectVersion(major, minor, release) {
        this.major = major
        this.minor = minor
        this.release = release
    }

    @Override
    String toString () {
        return major + '>>' + minor
    }

}

task printVersion {
    doLast {
        println "$version"
    }
}
任务配置

新建version.properties文件(和build.gradle同级):

major = 0
minor = 111
release = false

在build.gradle中编写脚本:

// 添加任务配置块
ext.versionFile = file('version.properties')
// 配置任务
task loadVersion {
    project.version = readVersion()
}

ProjectVersion readVersion() {
    logger.quiet 'reading the version file'
    // 如果文件不存在
    if (!versionFile.exists()) {
        throw new GradleScriptException('file not found', null)
    }

    Properties versionProps = new Properties()

    versionFile.withInputStream { stream -> versionProps.load(stream)}

    new ProjectVersion(versionProps.major.toInteger(), versionProps.minor.toInteger(), versionProps.release.toBoolean())

}

class ProjectVersion {
    // groovy 中会为属性自动添加getter/setter方法
    Integer major
    Integer minor
    Boolean release

    ProjectVersion(major, minor, release) {
        this.major = major
        this.minor = minor
        this.release = release
    }

    @Override
    String toString () {
        return major + '>>' + minor
    }

}

task printVersion {
    doLast {
        println "$version"
    }
}

在命令行中执行命令gradle printVersion,即可看到version已经是version.properties中定义的值了。

生命周期

在这里插入图片描述
配置完成后会执行whenReady方法:

// 添加任务配置块
ext.versionFile = file('version.properties')
// 配置任务
task loadVersion {
    project.version = readVersion()
}

ProjectVersion readVersion() {
    logger.quiet 'reading the version file'
    // 如果文件不存在
    if (!versionFile.exists()) {
        throw new GradleScriptException('file not found', null)
    }

    Properties versionProps = new Properties()

    versionFile.withInputStream { stream -> versionProps.load(stream)}

    new ProjectVersion(versionProps.major.toInteger(), versionProps.minor.toInteger(), versionProps.release.toBoolean())

}

class ProjectVersion {
    // groovy 中会为属性自动添加getter/setter方法
    Integer major
    Integer minor
    Boolean release

    ProjectVersion(major, minor, release) {
        this.major = major
        this.minor = minor
        this.release = release
    }

    @Override
    String toString () {
        return major + '>>' + minor
    }

}

task printVersion {
    doLast {
        println "$version"
    }
}

// 在配置阶段后执行,修改了version
gradle.taskGraph.whenReady { TaskExecutionGraph taskExecutionGraph ->
    if (taskExecutionGraph.hasTask(printVersion)) {
        version = "12"
    }
}

在命令行中执行这个任务,会发现这个version发生了变化。

配置Listener监听

// 添加任务配置块
ext.versionFile = file('version.properties')
// 配置任务
task loadVersion {
    project.version = readVersion()
}

ProjectVersion readVersion() {
    logger.quiet 'reading the version file'
    // 如果文件不存在
    if (!versionFile.exists()) {
        throw new GradleScriptException('file not found', null)
    }

    Properties versionProps = new Properties()

    versionFile.withInputStream { stream -> versionProps.load(stream)}

    new ProjectVersion(versionProps.major.toInteger(), versionProps.minor.toInteger(), versionProps.release.toBoolean())

}

class ProjectVersion {
    // groovy 中会为属性自动添加getter/setter方法
    Integer major
    Integer minor
    Boolean release

    ProjectVersion(major, minor, release) {
        this.major = major
        this.minor = minor
        this.release = release
    }

    @Override
    String toString () {
        return major + '>>' + minor
    }

}

task printVersion {
    doLast {
        println "$version"
    }
}

gradle.taskGraph.whenReady { TaskExecutionGraph taskExecutionGraph ->
    println 'whenReady'
    if (taskExecutionGraph.hasTask(printVersion)) {
        version = "12"
    }
}
// 实现TaskExecutionGraphListener接口
class VersionListener implements TaskExecutionGraphListener {

    @Override
    void graphPopulated(TaskExecutionGraph taskExecutionGraph) {
        if (taskExecutionGraph.hasTask(":printVersion")) {
            def tasks = taskExecutionGraph.allTasks
            for (Task t: tasks) {
                if (t.name == 'printVersion') {
                    t.project.version = 14
                }
            }
        }
    }
}
// 实例化
def versionListener = new VersionListener()
// 注册监听
gradle.taskGraph.addTaskExecutionGraphListener(versionListener)

监听后于gradle.taskGraph.whenReady执行。

依赖管理

在这里插入图片描述
检查依赖:
build.gradle

apply plugin: 'java'
repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE'
}

执行build dependencies

$ gradle dependencies
Starting a Gradle Daemon, 1 busy and 4 stopped Daemons could not be reused, use --status for details

> Task :dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

annotationProcessor - Annotation processors and their dependencies for source set 'main'.
No dependencies

apiElements - API elements for main. (n)
No dependencies

archives - Configuration for archive artifacts.
No dependencies

compile - Dependencies for source set 'main' (deprecated, use 'implementation' instead).
No dependencies

compileClasspath - Compile classpath for source set 'main'.
No dependencies

compileOnly - Compile only dependencies for source set 'main'.
No dependencies

default - Configuration for default artifacts.
No dependencies

implementation - Implementation only dependencies for source set 'main'. (n)
No dependencies

runtime - Runtime dependencies for source set 'main' (deprecated, use 'runtimeOnly' instead).
No dependencies

runtimeClasspath - Runtime classpath of source set 'main'.
No dependencies

runtimeElements - Elements of runtime for main. (n)
No dependencies

runtimeOnly - Runtime only dependencies for source set 'main'. (n)
No dependencies

testAnnotationProcessor - Annotation processors and their dependencies for source set 'test'.
No dependencies

testCompile - Dependencies for source set 'test' (deprecated, use 'testImplementation' instead).
\--- org.springframework.boot:spring-boot-starter-test:2.1.2.RELEASE
     +--- org.springframework.boot:spring-boot-starter:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot:2.1.2.RELEASE
     |    |    +--- org.springframework:spring-core:5.1.4.RELEASE
     |    |    |    \--- org.springframework:spring-jcl:5.1.4.RELEASE
     |    |    \--- org.springframework:spring-context:5.1.4.RELEASE
     |    |         +--- org.springframework:spring-aop:5.1.4.RELEASE
     |    |         |    +--- org.springframework:spring-beans:5.1.4.RELEASE
     |    |         |    |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-beans:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         \--- org.springframework:spring-expression:5.1.4.RELEASE
     |    |              \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE
     |    |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:2.1.2.RELEASE
     |    |    +--- ch.qos.logback:logback-classic:1.2.3
     |    |    |    +--- ch.qos.logback:logback-core:1.2.3
     |    |    |    \--- org.slf4j:slf4j-api:1.7.25
     |    |    +--- org.apache.logging.log4j:log4j-to-slf4j:2.11.1
     |    |    |    +--- org.slf4j:slf4j-api:1.7.25
     |    |    |    \--- org.apache.logging.log4j:log4j-api:2.11.1
     |    |    \--- org.slf4j:jul-to-slf4j:1.7.25
     |    |         \--- org.slf4j:slf4j-api:1.7.25
     |    +--- javax.annotation:javax.annotation-api:1.3.2
     |    +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    \--- org.yaml:snakeyaml:1.23
     +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE
     |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     +--- org.springframework.boot:spring-boot-test-autoconfigure:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE (*)
     |    \--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE (*)
     +--- com.jayway.jsonpath:json-path:2.4.0
     |    +--- net.minidev:json-smart:2.3
     |    |    \--- net.minidev:accessors-smart:1.2
     |    |         \--- org.ow2.asm:asm:5.0.4
     |    \--- org.slf4j:slf4j-api:1.7.25
     +--- junit:junit:4.12
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.assertj:assertj-core:3.11.1
     +--- org.mockito:mockito-core:2.23.4
     |    +--- net.bytebuddy:byte-buddy:1.9.3
     |    +--- net.bytebuddy:byte-buddy-agent:1.9.3
     |    \--- org.objenesis:objenesis:2.6
     +--- org.hamcrest:hamcrest-core:1.3
     +--- org.hamcrest:hamcrest-library:1.3
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.skyscreamer:jsonassert:1.5.0
     |    \--- com.vaadin.external.google:android-json:0.0.20131108.vaadin1
     +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     +--- org.springframework:spring-test:5.1.4.RELEASE
     |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     \--- org.xmlunit:xmlunit-core:2.6.2

testCompileClasspath - Compile classpath for source set 'test'.
\--- org.springframework.boot:spring-boot-starter-test:2.1.2.RELEASE
     +--- org.springframework.boot:spring-boot-starter:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot:2.1.2.RELEASE
     |    |    +--- org.springframework:spring-core:5.1.4.RELEASE
     |    |    |    \--- org.springframework:spring-jcl:5.1.4.RELEASE
     |    |    \--- org.springframework:spring-context:5.1.4.RELEASE
     |    |         +--- org.springframework:spring-aop:5.1.4.RELEASE
     |    |         |    +--- org.springframework:spring-beans:5.1.4.RELEASE
     |    |         |    |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-beans:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         \--- org.springframework:spring-expression:5.1.4.RELEASE
     |    |              \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE
     |    |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:2.1.2.RELEASE
     |    |    +--- ch.qos.logback:logback-classic:1.2.3
     |    |    |    +--- ch.qos.logback:logback-core:1.2.3
     |    |    |    \--- org.slf4j:slf4j-api:1.7.25
     |    |    +--- org.apache.logging.log4j:log4j-to-slf4j:2.11.1
     |    |    |    +--- org.slf4j:slf4j-api:1.7.25
     |    |    |    \--- org.apache.logging.log4j:log4j-api:2.11.1
     |    |    \--- org.slf4j:jul-to-slf4j:1.7.25
     |    |         \--- org.slf4j:slf4j-api:1.7.25
     |    +--- javax.annotation:javax.annotation-api:1.3.2
     |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE
     |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     +--- org.springframework.boot:spring-boot-test-autoconfigure:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE (*)
     |    \--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE (*)
     +--- com.jayway.jsonpath:json-path:2.4.0
     |    +--- net.minidev:json-smart:2.3
     |    |    \--- net.minidev:accessors-smart:1.2
     |    |         \--- org.ow2.asm:asm:5.0.4
     |    \--- org.slf4j:slf4j-api:1.7.25
     +--- junit:junit:4.12
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.assertj:assertj-core:3.11.1
     +--- org.mockito:mockito-core:2.23.4
     |    +--- net.bytebuddy:byte-buddy:1.9.3
     |    +--- net.bytebuddy:byte-buddy-agent:1.9.3
     |    \--- org.objenesis:objenesis:2.6
     +--- org.hamcrest:hamcrest-core:1.3
     +--- org.hamcrest:hamcrest-library:1.3
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.skyscreamer:jsonassert:1.5.0
     |    \--- com.vaadin.external.google:android-json:0.0.20131108.vaadin1
     +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     +--- org.springframework:spring-test:5.1.4.RELEASE
     |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     \--- org.xmlunit:xmlunit-core:2.6.2

testCompileOnly - Compile only dependencies for source set 'test'.
No dependencies

testImplementation - Implementation only dependencies for source set 'test'. (n)
No dependencies

testRuntime - Runtime dependencies for source set 'test' (deprecated, use 'testRuntimeOnly' instead).
\--- org.springframework.boot:spring-boot-starter-test:2.1.2.RELEASE
     +--- org.springframework.boot:spring-boot-starter:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot:2.1.2.RELEASE
     |    |    +--- org.springframework:spring-core:5.1.4.RELEASE
     |    |    |    \--- org.springframework:spring-jcl:5.1.4.RELEASE
     |    |    \--- org.springframework:spring-context:5.1.4.RELEASE
     |    |         +--- org.springframework:spring-aop:5.1.4.RELEASE
     |    |         |    +--- org.springframework:spring-beans:5.1.4.RELEASE
     |    |         |    |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-beans:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         \--- org.springframework:spring-expression:5.1.4.RELEASE
     |    |              \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE
     |    |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:2.1.2.RELEASE
     |    |    +--- ch.qos.logback:logback-classic:1.2.3
     |    |    |    +--- ch.qos.logback:logback-core:1.2.3
     |    |    |    \--- org.slf4j:slf4j-api:1.7.25
     |    |    +--- org.apache.logging.log4j:log4j-to-slf4j:2.11.1
     |    |    |    +--- org.slf4j:slf4j-api:1.7.25
     |    |    |    \--- org.apache.logging.log4j:log4j-api:2.11.1
     |    |    \--- org.slf4j:jul-to-slf4j:1.7.25
     |    |         \--- org.slf4j:slf4j-api:1.7.25
     |    +--- javax.annotation:javax.annotation-api:1.3.2
     |    +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    \--- org.yaml:snakeyaml:1.23
     +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE
     |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     +--- org.springframework.boot:spring-boot-test-autoconfigure:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE (*)
     |    \--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE (*)
     +--- com.jayway.jsonpath:json-path:2.4.0
     |    +--- net.minidev:json-smart:2.3
     |    |    \--- net.minidev:accessors-smart:1.2
     |    |         \--- org.ow2.asm:asm:5.0.4
     |    \--- org.slf4j:slf4j-api:1.7.25
     +--- junit:junit:4.12
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.assertj:assertj-core:3.11.1
     +--- org.mockito:mockito-core:2.23.4
     |    +--- net.bytebuddy:byte-buddy:1.9.3
     |    +--- net.bytebuddy:byte-buddy-agent:1.9.3
     |    \--- org.objenesis:objenesis:2.6
     +--- org.hamcrest:hamcrest-core:1.3
     +--- org.hamcrest:hamcrest-library:1.3
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.skyscreamer:jsonassert:1.5.0
     |    \--- com.vaadin.external.google:android-json:0.0.20131108.vaadin1
     +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     +--- org.springframework:spring-test:5.1.4.RELEASE
     |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     \--- org.xmlunit:xmlunit-core:2.6.2

testRuntimeClasspath - Runtime classpath of source set 'test'.
\--- org.springframework.boot:spring-boot-starter-test:2.1.2.RELEASE
     +--- org.springframework.boot:spring-boot-starter:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot:2.1.2.RELEASE
     |    |    +--- org.springframework:spring-core:5.1.4.RELEASE
     |    |    |    \--- org.springframework:spring-jcl:5.1.4.RELEASE
     |    |    \--- org.springframework:spring-context:5.1.4.RELEASE
     |    |         +--- org.springframework:spring-aop:5.1.4.RELEASE
     |    |         |    +--- org.springframework:spring-beans:5.1.4.RELEASE
     |    |         |    |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-beans:5.1.4.RELEASE (*)
     |    |         +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    |         \--- org.springframework:spring-expression:5.1.4.RELEASE
     |    |              \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE
     |    |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     |    +--- org.springframework.boot:spring-boot-starter-logging:2.1.2.RELEASE
     |    |    +--- ch.qos.logback:logback-classic:1.2.3
     |    |    |    +--- ch.qos.logback:logback-core:1.2.3
     |    |    |    \--- org.slf4j:slf4j-api:1.7.25
     |    |    +--- org.apache.logging.log4j:log4j-to-slf4j:2.11.1
     |    |    |    +--- org.slf4j:slf4j-api:1.7.25
     |    |    |    \--- org.apache.logging.log4j:log4j-api:2.11.1
     |    |    \--- org.slf4j:jul-to-slf4j:1.7.25
     |    |         \--- org.slf4j:slf4j-api:1.7.25
     |    +--- javax.annotation:javax.annotation-api:1.3.2
     |    +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     |    \--- org.yaml:snakeyaml:1.23
     +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE
     |    \--- org.springframework.boot:spring-boot:2.1.2.RELEASE (*)
     +--- org.springframework.boot:spring-boot-test-autoconfigure:2.1.2.RELEASE
     |    +--- org.springframework.boot:spring-boot-test:2.1.2.RELEASE (*)
     |    \--- org.springframework.boot:spring-boot-autoconfigure:2.1.2.RELEASE (*)
     +--- com.jayway.jsonpath:json-path:2.4.0
     |    +--- net.minidev:json-smart:2.3
     |    |    \--- net.minidev:accessors-smart:1.2
     |    |         \--- org.ow2.asm:asm:5.0.4
     |    \--- org.slf4j:slf4j-api:1.7.25
     +--- junit:junit:4.12
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.assertj:assertj-core:3.11.1
     +--- org.mockito:mockito-core:2.23.4
     |    +--- net.bytebuddy:byte-buddy:1.9.3
     |    +--- net.bytebuddy:byte-buddy-agent:1.9.3
     |    \--- org.objenesis:objenesis:2.6
     +--- org.hamcrest:hamcrest-core:1.3
     +--- org.hamcrest:hamcrest-library:1.3
     |    \--- org.hamcrest:hamcrest-core:1.3
     +--- org.skyscreamer:jsonassert:1.5.0
     |    \--- com.vaadin.external.google:android-json:0.0.20131108.vaadin1
     +--- org.springframework:spring-core:5.1.4.RELEASE (*)
     +--- org.springframework:spring-test:5.1.4.RELEASE
     |    \--- org.springframework:spring-core:5.1.4.RELEASE (*)
     \--- org.xmlunit:xmlunit-core:2.6.2

testRuntimeOnly - Runtime only dependencies for source set 'test'. (n)
No dependencies

(*) - dependencies omitted (listed previously)

A web-based, searchable dependency report is available by adding the --scan option.

BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed

像这样org.springframework:spring-core:5.1.4.RELEASE (*)后面带了(*)表示这个依赖被忽略了。因为多个jar包会引用。

依赖排除

下面的gradle中配置的spring-boot-starter-test要依赖junit 4.12,下面展示了从spring-boot-starter-test中排出junit4.12,然后引入了junit 4.10。通过命令gradle dependencies可以查看依赖情况!

apply plugin: 'java'
repositories {
    mavenCentral()
}

dependencies {
    testCompile (group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE') {
    	// 注意,gradle不允许排除指定版本的依赖
        exclude group: 'junit', module: 'junit'
    }

    testCompile group: 'junit', name: 'junit', version: '4.10'

}

通过transitive = false排除所有传递性依赖:

dependencies {
    testCompile (group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '2.1.2.RELEASE') {
    	transitive = false
    }
    // ....
}
动态指定版本

依赖的version属性写成latest.integration,或者n.+,比如1.+就是1开头的最后一个版本:

apply plugin: 'java'
repositories {
    mavenCentral()
}

dependencies {
	// 使用spring boot 1.+的最后一个版本
    testCompile (group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.+') {
    // 排出所有依赖
       transitive =false
    }
	// 使用junit的最后一个版本
    testCompile group: 'junit', name: 'junit', version: 'latest.integration'

}

指定仓库

repositories {
	// 指定本地仓库
    mavenLocal()
    // 指定maven中央仓库
    mavenCentral()
    // 指定自定义仓库
    maven {
        name 'my maven repository'
        url 'http://mymaven.com'
    }
}

gradle下载下来的jar文件默认存在 用户家目录/.gradle/caches/modules-2/files-2.1中的。

多模块项目构建

step.1 新建一个文件夹作作为父工程,并为其新建一个build.gradle文件,然后执行gradle projects

$ gradle projects

> Task :projects

------------------------------------------------------------
Root project
------------------------------------------------------------

Root project 'demo01'
No sub-projects

To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :tasks

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

step.2 新建settings.gradle,并键入以下内容

include 'sub1'
include 'sub2', 'sub3'

执行命令gradle projects:

$ gradle projects

> Task :projects

------------------------------------------------------------
Root project
------------------------------------------------------------

Root project 'demo01'
+--- Project ':sub1' # 这里的 : 号是用来分隔目录层次
+--- Project ':sub2'
\--- Project ':sub3'

To see a list of the tasks of a project, run gradle <project-path>:tasks
For example, try running gradle :sub1:tasks

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

settings对应的类:
在这里插入图片描述
settings处于实例化阶段
在这里插入图片描述
父工程中配置子模块:

ext.projectIds = ['group': 'com.gradle.demo', 'version': '1.0']

group = projectIds.group

version = projectIds.version

// 定义子模块sub1中的属性 : 只是用来表示层级关系的
project(':sub1') {
    group = projectIds.group
    version = projectIds.version
    apply plugin: 'java'
}

project(':sub2') {
    group = projectIds.group
    version = projectIds.version
    apply plugin: 'java'
	// 指定依赖sub1
	dependencies {
		compile project(':sub1')
	}

}

project(':sub3') {
    group = projectIds.group
    version = projectIds.version
    apply plugin: 'java'
    apply plugin: 'war'

    repositories {
        mavenCentral()
    }

    dependencies {
        testCompile 'junit:junit:4.12'
    }

}

下面在每个模块中都声明了group和version,也可以同时声明些属性:

allprojects {
    group = 'com.demo'
    version = '2.0'
}

也可以为所有的子模块添加属性:

// 为所有子模块添加了java插件
subprojects {
    apply plugin: 'java'
}

上面的所有操作,我们都没有指定子模块的路径或者是新建一个子模块,仅仅是在settings.gradle中声明了包含的子模块而已,那么这个子模块到底在哪呢?
其实子模块在settings.gradle所在项目文件目录下,每一个子模块对应一个名字,名字就是include引入时的名字,可以事先好建立,也可以执行gradle build,gradle会自动创建。

上面的方式把父项目和子项目的配置都写在了一个文件中,下面介绍每个模块引用自己的配置:

// 子模块
include 'sub1', 'sub2', 'sub3'

// 设置根项目名称
rootProject.name = 'todo'

//迭代访问所有根目录下的子项目,设置自定义的构建脚本名称
rootProject.children.each {
	// sub1的构建脚本为sub1.gradle,sub2为sub2.gradle,sub3为sub3.gradle
    it.buildFileName = it.name + '.gradle'
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值