Gradle基本入门

Gradle快速入门

和Maven一样,Gradle只是提供了构建项目的一个框架,真正起作用的是Plugin。Gradle在默认情况下为我们提供了许多常用的Plugin,其中包括有构建Java项目的Plugin,还有War,Ear等。与Maven不同的是,Gradle不提供内建的项目生命周期管理,只是java Plugin向Project中添加了许多Task,这些Task依次执行,为我们营造了一种如同Maven般项目构建周期。

现在我们都在谈领域驱动设计,Gradle本身的领域对象主要有Project和Task。Project为Task提供了执行上下文,所有的Plugin要么向Project中添加用于配置的Property,要么向Project中添加不同的Task。一个Task表示一个逻辑上较为独立的执行过程,比如编译Java源代码,拷贝文件,打包Jar文件,甚至可以是执行一个系统命令或者调用Ant。另外,一个Task可以读取和设置Project的Property以完成特定的操作。

创建步骤

  • 创建文件夹并初始化
mkdir gradle_demo

cd gradle_demo

gradle init
  • 查看结构目录
    终端输入:
 tree -f

如果你没有安装tree,请先安装tree,如下:

brew install tree

得到的目录如下:

.
├── ./build.gradle
├── ./gradle
│   └── ./gradle/wrapper
│       ├── ./gradle/wrapper/gradle-wrapper.jar
│       └── ./gradle/wrapper/gradle-wrapper.properties
├── ./gradlew
├── ./gradlew.bat
└── ./settings.gradle

build.gradle

gradle项目自动编译的时候要读取的配置文件。比如指定项目的依赖包等。
build.grade有两个,一个是全局的,一个是在模块里面。
全局的build.grade主要设置的是声明仓库源,gradle的版本号说明等。

gradle

gradlew / gradlew.bat

自动完成 gradle 环境的脚本,在 linux 和 mac 下直接运行 gradlew 会自动完成 gradle 环境的搭建。

settings.gradle

整个项目的管理,比如这个项目包含哪些模块等

Task

让我们来看一个最简单的Task,打开gradle_demo文件夹下的build.gradle文件,内容如下:

/*
 * This build file was generated by the Gradle 'init' task.
 *
 * This generated file contains a commented-out sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * user guide available at https://docs.gradle.org/4.1/userguide/tutorial_java_projects.html
 */

/*
// Apply the java plugin to add support for Java
apply plugin: 'java'

// In this section you declare where to find the dependencies of your project
repositories {
    // Use 'jcenter' for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    jcenter()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    // The production code uses the SLF4J logging API at compile time
    compile 'org.slf4j:slf4j-api:1.7.25'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile 'junit:junit:4.12'
}
*/

这里面全是注释,并没有Task,接下来我们新建一个Task

task helloword << {
    println 'hello gradle!'
}

在与build.gradle相同的目录下执行:

gradle helloword 

结果:


> Configure project :
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
        at build_dm49rdwdh0ayv2low2to9ie29.run(/Users/liyang/gradle_demo/build.gradle:33)

> Task :helloword
hello gradle!

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

在默认情况下,Gradle将当前目录下的build.gradle文件作为项目的构建文件。在上面的例子中,我们创建了一个名为helloword的Task,在执行gradle命令时,我们指定执行这个helloWorld Task。

Gradle在默认情况下为我们提供了几个常用的Task,比如查看Project的Properties、显示当前Project中定义的所有Task等。可以通过一下命令查看Project中所有的Task:

gradle tasks --all

输出结果:


> Configure project :
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
        at build_dm49rdwdh0ayv2low2to9ie29.run(/Users/liyang/gradle_demo/build.gradle:33)

> Task :tasks

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

Other tasks
-----------
helloword


BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

可看出,除了我们自己定义的helloWorld之外,Gradle还默认为我们提供了dependencies、projects和properties等Task。dependencies用于显示Project的依赖信息,projects用于显示所有Project,包括根Project和子Project,而properties则用于显示一个Project所包含的所有Property。

在默认情况下,Gradle已经为Project添加了很多Property,我们可以调用以下命令进行查看:

gradle properties

输出结果:

> Configure project :
The Task.leftShift(Closure) method has been deprecated and is scheduled to be removed in Gradle 5.0. Please use Task.doLast(Action) instead.
        at build_dm49rdwdh0ayv2low2to9ie29.run(/Users/liyang/gradle_demo/build.gradle:33)

> Task :properties

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

allprojects: [root project 'gradle_demo']
ant: org.gradle.api.internal.project.DefaultAntBuilder@76dd470c
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@5dbbe35f
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@41de9bb8
asDynamicObject: DynamicObject for root project 'gradle_demo'
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@65a1e31b
buildDir: /Users/liyang/gradle_demo/build
buildFile: /Users/liyang/gradle_demo/build.gradle
buildScriptSource: org.gradle.groovy.scripts.UriScriptSource@79d83d84
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@7bfb88fb
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@4e4dcf67
components: SoftwareComponentInternal set
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@241e448e
configurationTargetIdentifier: org.gradle.configuration.ConfigurationTargetIdentifier$1@1c927994
configurations: configuration container
convention: org.gradle.api.internal.plugins.DefaultConvention@3b0996ad
defaultTasks: []
deferredProjectConfiguration: org.gradle.api.internal.project.DeferredProjectConfiguration@1b1f505c
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@4d735d85
depth: 0
description: null
displayName: root project 'gradle_demo'
ext: org.gradle.api.internal.plugins.DefaultExtraPropertiesExtension@42a2d366
extensions: org.gradle.api.internal.plugins.DefaultConvention@3b0996ad
fileOperations: org.gradle.api.internal.file.DefaultFileOperations@35698961
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@5415b220
gradle: build 'gradle_demo'
group: 
helloword: task ':helloword'
identityPath: :
inheritedScope: org.gradle.api.internal.ExtensibleDynamicObject$InheritedDynamicObject@35d5252
layout: org.gradle.api.internal.file.DefaultProjectLayout@57b098bc
logger: org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger@2e6b31aa
logging: org.gradle.internal.logging.services.DefaultLoggingManager@571612f5
modelRegistry: org.gradle.model.internal.registry.DefaultModelRegistry@3eb01587
modelSchemaStore: org.gradle.model.internal.manage.schema.extract.DefaultModelSchemaStore@6d161f95
module: org.gradle.api.internal.artifacts.ProjectBackedModule@739470fa
name: gradle_demo
normalization: org.gradle.normalization.internal.DefaultInputNormalizationHandler_Decorated@1a0785fc
objects: org.gradle.api.internal.model.DefaultObjectFactory@7d61bdf3
parent: null
parentIdentifier: null
path: :
pluginManager: org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@43c393f5
plugins: [org.gradle.api.plugins.HelpTasksPlugin@d968fd4]
processOperations: org.gradle.api.internal.file.DefaultFileOperations@35698961
project: root project 'gradle_demo'
projectConfigurator: org.gradle.api.internal.project.BuildOperationCrossProjectConfigurator@1e74c6af
projectDir: /Users/liyang/gradle_demo
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@387a88f8
projectPath: :
projectRegistry: org.gradle.api.internal.project.DefaultProjectRegistry@48042421
properties: {...}
providers: org.gradle.api.internal.provider.DefaultProviderFactory@17075aef
repositories: repository container
resources: org.gradle.api.internal.resources.DefaultResourceHandler@2ffeb71e
rootDir: /Users/liyang/gradle_demo
rootProject: root project 'gradle_demo'
scriptHandlerFactory: org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@432fc751
scriptPluginFactory: org.gradle.configuration.ScriptPluginFactorySelector@2ae3d639
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$4@79e21a8
services: ProjectScopeServices
standardOutputCapture: org.gradle.internal.logging.services.DefaultLoggingManager@571612f5
state: project state 'EXECUTED'
status: release
subprojects: []
tasks: task set
version: unspecified


BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed

在以上Property中,allprojects表示所有的Project,这里只包含一个根Project,在多项目构建中,它将包含多个Project;buildDir表示构建结果的输出目录;我们自己定义的helloWorld和copyFile也成为了Project中的Property。另外,Project还包括用于执行Ant命令的DefaultAntBuilder(Property名为ant)和Project的描述属性description。

    原文作者:ProZoom
    原文地址: https://www.jianshu.com/p/b9de1380995b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞