Gradle

2020-12-23  本文已影响0人  GaoXiaoGao

https://gradle.org/

1. 安装 点击"Install Gradle"

安装1.PNG

2.下载 点击Binary-only

安装2.PNG

3.添加到环境变量Path中

//解压 复制到bin的路径 添加到环境变量中
C:\tools\gradle-6.7.1\bin

4.打开IDEA新建Gradle工程,选择java

如果使用的是其他版本的Gradle,可以配置成本地的Gradle,打开gradle-wrapper.properties distributionUrl 修改为

distributionUrl=file:///C:/tools/gradle-6.7.1-bin.zip

5.将build.gradle修改为build.gradle.kts

环境配置好后,可以在build.gradle.kts写一些配置

6.配置Gradle支持编译Kotlin

在build.gradle.kts文件中配置如下,这样编写kotlin代码也可以编译执行

plugins {
    application
    kotlin("jvm") version "1.3.61" //支持编译kotlin代码
}

application{
    mainClassName="Main"  //Main是执行的class入口
}

dependencies{
    //添加kotlin的标准库
    compile(kotlin("stdlib"))
}

repositories{
    jcenter()
}

7.如何发布工程

双击工程右侧 distZip如下图


发布工程1.PNG

运行完成后会在工程的build目录下生成发布包,如下图

发布工程2.PNG

8.gradle中的task

在build.gradle.kts中输入以下代码

task("hello",{
    println("hello i am gradle task")
})

刷新后在右侧tasks中会看到一个名为 hello的任务


任务.PNG

9.任务的依赖

在build.gradle.kts中有以下任务

task("opendoor",{
})

task("putelephant",{
}).dependsOn("opendoor")


task("closedoor",{
}).dependsOn("putelephant")

putelephant任务依赖于(dependsOn)opendoor任务,当双击运行
putelephant任务时会执行

> Task :opendoor UP-TO-DATE
> Task :putelephant UP-TO-DATE

双击closedoor任务则执行,反映的都是任务的依赖

> Task :opendoor UP-TO-DATE
> Task :putelephant UP-TO-DATE
> Task :closedoor UP-TO-DATE

10.任务task的生命周期

任务有扫描和执行两个状态

任务默认在扫描的时候会按照顺序执行一下,如果想使得任务在扫描的时候不执行
而是在真正执行的时候才执行需要通过doFirst包裹代码

task("opendoor",{
    var name="hello"; //扫描时执行
    doFirst{//运行时执行的
        println("1开冰箱");
    }
//    doLast{} //运行时执行的
})

task("putelephant",{
    doFirst{
        println("2放入大象到冰箱");
    }
}).dependsOn("opendoor")


task("closedoor",{
    doFirst{
        println("3关冰箱门");
    }
}).dependsOn("putelephant")

11.task的任务集

任务集采用tasks关键字,里面可以定义多个任务

tasks{

    "opendoor" {

    }

    "putelephant" {

    }.dependsOn("opendoor")

    "closedoor" {

    }.dependsOn("putelephant")
}

12.Gradle的默认任务和默认配置

配置文件中没有配置任务任务时
在命令窗口执行
$ gradle tasks
可以查看默认的任务

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 'Desktop'.
components - Displays the components produced by root project 'Desktop'. [incubating]
dependencies - Displays all dependencies declared in root project 'Desktop'.
dependencyInsight - Displays the insight into a specific dependency in root project 'Desktop'.
dependentComponents - Displays the dependent components of components in root project 'Desktop'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'Desktop'. [incubating]
outgoingVariants - Displays the outgoing variants of root project 'Desktop'.
projects - Displays the sub-projects of root project 'Desktop'.
properties - Displays the properties of root project 'Desktop'.
tasks - Displays the tasks runnable from root project 'Desktop'.

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

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

新建任务打印工程的默认配置,刷新执行

task("print project",{
    project.properties.forEach { t, any ->
        println("$t : $any")
    }
})

结果如下

Configure project :
android.injected.build.model.only.advanced : true
parent : null
classLoaderScope : org.gradle.api.internal.initialization.DefaultClassLoaderScope@52cd6ff3
buildDir : D:\workspace\kotlinWorkspace\LeanGradle\build
configurations : configuration container
plugins : [org.gradle.api.plugins.HelpTasksPlugin@192081fa, org.gradle.buildinit.plugins.BuildInitPlugin@4e47721a, org.gradle.buildinit.plugins.WrapperPlugin@5d207742, org.gradle.kotlin.dsl.provider.plugins.KotlinScriptRootPlugin@3e78be8, org.gradle.kotlin.dsl.provider.plugins.KotlinScriptBasePlugin@1ed5f53f]
scriptHandlerFactory : org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@6b77835d
gradleKotlinDsl.projectAccessorsClassPath : AccessorsClassPath(bin=[C:\Users\andro\.gradle\caches\6.7.1\kotlin-dsl\accessors\40jl4o21zldbaaeib0mw0rzfa\classes], src=[C:\Users\andro\.gradle\caches\6.7.1\kotlin-dsl\accessors\40jl4o21zldbaaeib0mw0rzfa\sources])
objects : org.gradle.api.internal.model.DefaultObjectFactory@35337316
logger : org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger@c49b6ff
deferredProjectConfiguration : org.gradle.api.internal.project.DeferredProjectConfiguration@ab41693
rootDir : D:\workspace\kotlinWorkspace\LeanGradle
project : root project 'LeanGradle'
projectRegistry : org.gradle.api.internal.project.DefaultProjectRegistry@3b7976f7
path : :
normalization : org.gradle.normalization.internal.DefaultInputNormalizationHandler_Decorated@6cc377ae
repositories : repository container
childProjects : {}
android.injected.invoked.from.ide : true
model : project :
scriptPluginFactory : org.gradle.configuration.ScriptPluginFactorySelector@424602e3
state : project state 'EXECUTING'
serviceRegistryFactory : org.gradle.internal.service.scopes.ProjectScopeServices$$Lambda$583/1335897986@63bc6fd7
tasks : task set
group : 
artifacts : org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@686c94b6
ext : org.gradle.internal.extensibility.DefaultExtraPropertiesExtension@18528982
projectDir : D:\workspace\kotlinWorkspace\LeanGradle
dependencyLocking : org.gradle.internal.locking.DefaultDependencyLockingHandler_Decorated@6fdbf321
print project : task ':print project'
configurationTargetIdentifier : org.gradle.configuration.ConfigurationTargetIdentifier$1@1d78a523
projectEvaluationBroadcaster : ProjectEvaluationListener broadcast
projectPath : :
module : org.gradle.api.internal.artifacts.ProjectBackedModule@2dee7ef0
inheritedScope : org.gradle.internal.extensibility.ExtensibleDynamicObject$InheritedDynamicObject@113d4b1e
android.injected.build.model.only.versioned : 3
version : unspecified
script : false
android.injected.build.model.only : true
dependencies : org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@1dafde22
fileResolver : org.gradle.api.internal.file.BaseDirFileResolver@2ddd644d
extensions : org.gradle.internal.extensibility.DefaultConvention@75548d68
modelRegistry : org.gradle.model.internal.registry.DefaultModelRegistry@e4a4d67
projectEvaluator : org.gradle.configuration.project.LifecycleProjectEvaluator@6d77cc42
projectConfigurator : org.gradle.api.internal.project.BuildOperationCrossProjectConfigurator@2b4e22ad
name : LeanGradle
logging : org.gradle.internal.logging.services.DefaultLoggingManager@7a20d561
configurationActions : org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@26dd8e37
buildscript : org.gradle.api.internal.initialization.DefaultScriptHandler@759b5372
status : release
processOperations : org.gradle.process.internal.DefaultExecActionFactory$DecoratingExecActionFactory@2f9a5c26
subprojects : []
components : SoftwareComponentInternal set
asDynamicObject : DynamicObject for root project 'LeanGradle'
displayName : root project 'LeanGradle'
identityPath : :
parentIdentifier : null
description : null
antBuilderFactory : org.gradle.api.internal.project.DefaultAntBuilderFactory@536d1f69
buildPath : :
fileOperations : org.gradle.api.internal.file.DefaultFileOperations@198b9f05
pluginManager : org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@36a44f85
standardOutputCapture : org.gradle.internal.logging.services.DefaultLoggingManager@7a20d561
android.injected.build.model.disable.src.download : false
defaultTasks : []
modelSchemaStore : org.gradle.model.internal.manage.schema.extract.DefaultModelSchemaStore@2bde4a8f
class : class org.gradle.api.internal.project.DefaultProject_Decorated
buildScriptSource : org.gradle.groovy.scripts.TextResourceScriptSource@4ba24e1b
convention : org.gradle.internal.extensibility.DefaultConvention@75548d68
allprojects : [root project 'LeanGradle']
baseClassLoaderScope : org.gradle.api.internal.initialization.DefaultClassLoaderScope@708f9651
ant : org.gradle.api.internal.project.DefaultAntBuilder@35395cf2
resources : org.gradle.api.internal.resources.DefaultResourceHandler@2175f5b7
services : ProjectScopeServices
gradle : build 'LeanGradle'
layout : org.gradle.api.internal.file.DefaultProjectLayout@787eb514
taskThatOwnsThisObject : null
buildFile : D:\workspace\kotlinWorkspace\LeanGradle\build.gradle.kts
depth : 0
mutationState : project :
listenerBuildOperationDecorator : org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator@744f8954
rootProject : root project 'LeanGradle'
modelIdentityDisplayName : null
properties : {android.injected.build.model.only.advanced=true, parent=null, classLoaderScope=org.gradle.api.internal.initialization.DefaultClassLoaderScope@52cd6ff3, buildDir=D:\workspace\kotlinWorkspace\LeanGradle\build, configurations=configuration container, plugins=[org.gradle.api.plugins.HelpTasksPlugin@192081fa, org.gradle.buildinit.plugins.BuildInitPlugin@4e47721a, org.gradle.buildinit.plugins.WrapperPlugin@5d207742, org.gradle.kotlin.dsl.provider.plugins.KotlinScriptRootPlugin@3e78be8, org.gradle.kotlin.dsl.provider.plugins.KotlinScriptBasePlugin@1ed5f53f], scriptHandlerFactory=org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@6b77835d, gradleKotlinDsl.projectAccessorsClassPath=AccessorsClassPath(bin=[C:\Users\andro\.gradle\caches\6.7.1\kotlin-dsl\accessors\40jl4o21zldbaaeib0mw0rzfa\classes], src=[C:\Users\andro\.gradle\caches\6.7.1\kotlin-dsl\accessors\40jl4o21zldbaaeib0mw0rzfa\sources]), objects=org.gradle.api.internal.model.DefaultObjectFactory@35337316, logger=org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger@c49b6ff, deferredProjectConfiguration=org.gradle.api.internal.project.DeferredProjectConfiguration@ab41693, rootDir=D:\workspace\kotlinWorkspace\LeanGradle, project=root project 'LeanGradle', projectRegistry=org.gradle.api.internal.project.DefaultProjectRegistry@3b7976f7, path=:, normalization=org.gradle.normalization.internal.DefaultInputNormalizationHandler_Decorated@6cc377ae, repositories=repository container, childProjects={}, android.injected.invoked.from.ide=true, model=project :, scriptPluginFactory=org.gradle.configuration.ScriptPluginFactorySelector@424602e3, state=project state 'EXECUTING', serviceRegistryFactory=org.gradle.internal.service.scopes.ProjectScopeServices$$Lambda$583/1335897986@63bc6fd7, tasks=task set, group=, artifacts=org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@686c94b6, ext=org.gradle.internal.extensibility.DefaultExtraPropertiesExtension@18528982, projectDir=D:\workspace\kotlinWorkspace\LeanGradle, dependencyLocking=org.gradle.internal.locking.DefaultDependencyLockingHandler_Decorated@6fdbf321, print project=task ':print project', configurationTargetIdentifier=org.gradle.configuration.ConfigurationTargetIdentifier$1@1d78a523, projectEvaluationBroadcaster=ProjectEvaluationListener broadcast, projectPath=:, module=org.gradle.api.internal.artifacts.ProjectBackedModule@2dee7ef0, inheritedScope=org.gradle.internal.extensibility.ExtensibleDynamicObject$InheritedDynamicObject@113d4b1e, android.injected.build.model.only.versioned=3, version=unspecified, script=false, android.injected.build.model.only=true, dependencies=org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@1dafde22, fileResolver=org.gradle.api.internal.file.BaseDirFileResolver@2ddd644d, extensions=org.gradle.internal.extensibility.DefaultConvention@75548d68, modelRegistry=org.gradle.model.internal.registry.DefaultModelRegistry@e4a4d67, projectEvaluator=org.gradle.configuration.project.LifecycleProjectEvaluator@6d77cc42, projectConfigurator=org.gradle.api.internal.project.BuildOperationCrossProjectConfigurator@2b4e22ad, name=LeanGradle, logging=org.gradle.internal.logging.services.DefaultLoggingManager@7a20d561, configurationActions=org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@26dd8e37, buildscript=org.gradle.api.internal.initialization.DefaultScriptHandler@759b5372, status=release, processOperations=org.gradle.process.internal.DefaultExecActionFactory$DecoratingExecActionFactory@2f9a5c26, subprojects=[], components=SoftwareComponentInternal set, asDynamicObject=DynamicObject for root project 'LeanGradle', displayName=root project 'LeanGradle', identityPath=:, parentIdentifier=null, description=null, antBuilderFactory=org.gradle.api.internal.project.DefaultAntBuilderFactory@536d1f69, buildPath=:, fileOperations=org.gradle.api.internal.file.DefaultFileOperations@198b9f05, pluginManager=org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@36a44f85, standardOutputCapture=org.gradle.internal.logging.services.DefaultLoggingManager@7a20d561, android.injected.build.model.disable.src.download=false, defaultTasks=[], modelSchemaStore=org.gradle.model.internal.manage.schema.extract.DefaultModelSchemaStore@2bde4a8f, class=class org.gradle.api.internal.project.DefaultProject_Decorated, buildScriptSource=org.gradle.groovy.scripts.TextResourceScriptSource@4ba24e1b, convention=org.gradle.internal.extensibility.DefaultConvention@75548d68, allprojects=[root project 'LeanGradle'], baseClassLoaderScope=org.gradle.api.internal.initialization.DefaultClassLoaderScope@708f9651, ant=org.gradle.api.internal.project.DefaultAntBuilder@35395cf2, resources=org.gradle.api.internal.resources.DefaultResourceHandler@2175f5b7, services=ProjectScopeServices, gradle=build 'LeanGradle', layout=org.gradle.api.internal.file.DefaultProjectLayout@787eb514, taskThatOwnsThisObject=null, buildFile=D:\workspace\kotlinWorkspace\LeanGradle\build.gradle.kts, depth=0, mutationState=project :, listenerBuildOperationDecorator=org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator@744f8954, rootProject=root project 'LeanGradle', modelIdentityDisplayName=null, properties=(this Map), providers=org.gradle.api.internal.provider.DefaultProviderFactory_Decorated@bee85e3}
providers : org.gradle.api.internal.provider.DefaultProviderFactory_Decorated@bee85e3

CONFIGURE SUCCESSFUL in 162ms

配置默认执行任务,当在命令窗口中执行gradle时,默认执行名为print的任务

defaultTasks("print")

13.Gradle增量式更新

例子如下
inputs 是输入
outputs 是输出
例子是统计目录下的文件,当src下的文件没有变化时,不会重新编译
当src下的文件有更新时,再次执行会重新编译

plugins {
    java
}
task("getsrcname",{

    inputs.dir("src") //输入
    outputs.files("info.txt") //输出

    doFirst{
        var srcdir=fileTree("src")
        var infotxt = file("info.txt")
        infotxt.writeText("");
        srcdir.forEach{
            if(it.isFile){
                Thread.sleep(1000)
                infotxt.appendText(it.absolutePath);
                infotxt.appendText("\r\n");
            }
        }
    }
})
上一篇下一篇

猜你喜欢

热点阅读