一、gradle入门

gradle是个工具,用于把项目自动构建为产品,具体来说就是自动编译、测试、打包和部署项目。

一、声明式构建和约定大于配置

gradle使用领域特定语言(Domain Specific Language)声明构建,该语言基于Groovy,Groovy也是一种语言用于java虚拟机。

gradle为Java、Groovy、Scala、web和OSGI项目提供开箱即用gradle的支持,即约定大于配置,即提供了很多默认配置,基本上不用你配置了,就能构建。

1、能够使用Ant任务和Maven仓库

2、增量构建

构建过程可以分好几个任务,有些任务要不要执行就看被操作对象是否修改过,有修改就执行该任务,没有修改就不执行。例如编译任务,假如源代码修改过,就执行编译,没有修改就不执行。

3、支持多项目构建也支持部分构建

项目之间有依赖,gradle帮我们处理依赖关系,也帮我们处理在构建项目之前要不要构建依赖的项目。

4、假如本地没有安装Gradle怎么办

使用GradleWapper构建

5、Gradle是开源的

二、安装Gradle(gradle 7.2)

事先要装好JDK,在cmd中输入 java -version 检验。

不需要安装Groovy。

下载gradle完整版

1、通过下载安装Gradle

解压后进入bin目录,在地址栏输入cmd,在命令行窗口输入 gradle -v,如下:

D:\gradle-7.4.2-all\bin>gradle -v

------------------------------------------------------------
Gradle 7.4.2
------------------------------------------------------------

Build time:   2022-03-31 15:25:29 UTC
Revision:     540473b8118064efcc264694cbcaa4b677f61041

Kotlin:       1.5.31
Groovy:       3.0.9
Ant:          Apache Ant(TM) version 1.10.11 compiled on July 10 2021
JVM:          1.8.0_201 (Oracle Corporation 25.201-b09)
OS:           Windows 7 6.1 amd64

说明安装成功了。

为了能在任何目录运行gradle命令,需要把bin目录加入path:

        设置环境变量GRADLE_HOME,把%GRADLE_HOME%\bin加入path。

如果我们想要把jvm选项加入gradle,可以使用JAVA_OPTS和GRADLE_OPTS这两个环境变量。

2、通过SDKMAN安装gradle

三、书写第一个构建脚本

在E:\java\tools\gradle\demo新建build.gradle,脚本如下:

task helloworld  {
	println('helloworld')
}

在该目录的地址栏输入cmd,打开命令行窗口,输入gradle helloworld,结果如下:

E:\java\tools\gradle\demo>gradle helloworld

> Configure project :
helloworld

BUILD SUCCESSFUL in 1s

如果要更简洁输出,加上-q,如下:

E:\java\tools\gradle\demo>gradle -q helloworld
helloworld

四、默认的gradle任务

为了使测试结果更加易懂,把代码修改为

task TasknameHello  {
	println('print hello')
}

执行 gradle -q tasks,结果如下:

E:\java\tools\gradle\demo>gradle -q tasks
print hello

------------------------------------------------------------
Tasks runnable from root project 'demo'
------------------------------------------------------------

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 'demo'.
dependencies - Displays all dependencies declared in root project 'demo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'demo'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'demo'.
projects - Displays the sub-projects of root project 'demo'.
properties - Displays the properties of root project 'demo'.
tasks - Displays the tasks runnable from root project 'demo'.

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

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

gradle内建任务在上面的Help tasks中展示,举例如下:

        help任务显示总的帮助信息:

E:\java\tools\gradle\demo>gradle -q help
print hello

Welcome to Gradle 7.2.

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

        properties任务显示该项目的属性及gradle内建属性,执行 gradle -q properties:

allprojects: [root project 'demo']
ant: org.gradle.api.internal.project.DefaultAntBuilder@20aa36ea
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@365a88d2
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@5d9da755
asDynamicObject: DynamicObject for root project 'demo'
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@60f9ec0c
buildDir: E:\java\tools\gradle\demo\build
buildFile: E:\java\tools\gradle\demo\build.gradle
buildPath: :
buildScriptSource: org.gradle.groovy.scripts.TextResourceScriptSource@11959b9f
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@73eb9d67
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@437c3b40
components: SoftwareComponentInternal set
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@6c4a26af
configurationTargetIdentifier: org.gradle.configuration.ConfigurationTargetIdentifier$1@51be11da
configurations: configuration container
convention: org.gradle.internal.extensibility.DefaultConvention@7e91be2f
crossProjectModelAccess: org.gradle.api.internal.project.DefaultCrossProjectModelAccess@5c952c86
defaultTasks: []
deferredProjectConfiguration: org.gradle.api.internal.project.DeferredProjectConfiguration@615716e5
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@40c6ebd4
//省略其他信息

        dependencies任务显示项目的依赖:

E:\java\tools\gradle\demo>gradle -q dependencies
print hello

------------------------------------------------------------
Root project 'demo'
------------------------------------------------------------

No configurations

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

        model任务显示gradle创建的model信息:

E:\java\tools\gradle\demo>gradle -q model
print hello

------------------------------------------------------------
Root project 'demo'
------------------------------------------------------------

+ tasks
      | Type:           org.gradle.model.ModelMap<org.gradle.api.Task>
      | Creator:        Project.<init>.tasks()
    + buildEnvironment
          | Type:       org.gradle.api.tasks.diagnostics.BuildEnvironmentReportTask
          | Value:      task ':buildEnvironment'
          | Creator:    Project.<init>.tasks.buildEnvironment()
          | Rules:
             ? copyToTaskContainer
    + components
          | Type:       org.gradle.api.reporting.components.ComponentReport
          | Value:      task ':components'
          | Creator:    Project.<init>.tasks.components()
          | Rules:
             ? copyToTaskContainer
    + dependencies
          | Type:       org.gradle.api.tasks.diagnostics.DependencyReportTask
          | Value:      task ':dependencies'
          | Creator:    Project.<init>.tasks.dependencies()
          | Rules:
             ? copyToTaskContainer
    + dependencyInsight
          | Type:       org.gradle.api.tasks.diagnostics.DependencyInsightReportTask
          | Value:      task ':dependencyInsight'
          | Creator:    Project.<init>.tasks.dependencyInsight()
          | Rules:
             ? copyToTaskContainer
    + dependentComponents
          | Type:       org.gradle.api.reporting.dependents.DependentComponentsReport
          | Value:      task ':dependentComponents'
          | Creator:    Project.<init>.tasks.dependentComponents()
          | Rules:
             ? copyToTaskContainer
    + help
          | Type:       org.gradle.configuration.Help
          | Value:      task ':help'
          | Creator:    Project.<init>.tasks.help()
          | Rules:
             ? copyToTaskContainer
    + init
          | Type:       org.gradle.buildinit.tasks.InitBuild
          | Value:      task ':init'
          | Creator:    Project.<init>.tasks.init()
          | Rules:
             ? copyToTaskContainer
    + javaToolchains
          | Type:       org.gradle.jvm.toolchain.internal.task.ShowToolchainsTask
          | Value:      task ':javaToolchains'
          | Creator:    Project.<init>.tasks.javaToolchains()
          | Rules:
             ? copyToTaskContainer
    + model
          | Type:       org.gradle.api.reporting.model.ModelReport
          | Value:      task ':model'
          | Creator:    Project.<init>.tasks.model()
          | Rules:
             ? copyToTaskContainer
    + outgoingVariants
          | Type:       org.gradle.api.tasks.diagnostics.OutgoingVariantsReportTask
          | Value:      task ':outgoingVariants'
          | Creator:    Project.<init>.tasks.outgoingVariants()
          | Rules:
             ? copyToTaskContainer
    + prepareKotlinBuildScriptModel
          | Type:       org.gradle.api.DefaultTask
          | Value:      task ':prepareKotlinBuildScriptModel'
          | Creator:    Project.<init>.tasks.prepareKotlinBuildScriptModel()
          | Rules:
             ? copyToTaskContainer
    + projects
          | Type:       org.gradle.api.tasks.diagnostics.ProjectReportTask
          | Value:      task ':projects'
          | Creator:    Project.<init>.tasks.projects()
          | Rules:
             ? copyToTaskContainer
    + properties
          | Type:       org.gradle.api.tasks.diagnostics.PropertyReportTask
          | Value:      task ':properties'
          | Creator:    Project.<init>.tasks.properties()
          | Rules:
             ? copyToTaskContainer
    + taskname_hello
          | Type:       org.gradle.api.DefaultTask
          | Value:      task ':taskname_hello'
          | Creator:    Project.<init>.tasks.taskname_hello()
          | Rules:
             ? copyToTaskContainer
    + tasks
          | Type:       org.gradle.api.tasks.diagnostics.TaskReportTask
          | Value:      task ':tasks'
          | Creator:    Project.<init>.tasks.tasks()
          | Rules:
             ? copyToTaskContainer
    + wrapper
          | Type:       org.gradle.api.tasks.wrapper.Wrapper
          | Value:      task ':wrapper'
          | Creator:    Project.<init>.tasks.wrapper()
          | Rules:
             ? copyToTaskContainer

五、任务名称缩写

gradle对项目执行某任务时,允许任务名称缩写,但缩写后的名称要保证唯一性,包括不与内建任务冲突。例如:缩写t,与tasks任务冲突了,所以可以用taskname或者驼峰写法TH:

E:\java\tools\gradle\demo>gradle -q t
print hello

------------------------------------------------------------
Tasks runnable from root project 'demo'
------------------------------------------------------------

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 'demo'.
dependencies - Displays all dependencies declared in root project 'demo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'demo'.
help - Displays a help message.
javaToolchains - Displays the detected java toolchains.
outgoingVariants - Displays the outgoing variants of root project 'demo'.
projects - Displays the sub-projects of root project 'demo'.
properties - Displays the properties of root project 'demo'.
tasks - Displays the tasks runnable from root project 'demo'.

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

To see more detail about a task, run gradle help --task <task>
E:\java\tools\gradle\demo>gradle -q taskname
print hello
E:\java\tools\gradle\demo>gradle -q TH
print hello

六、执行多任务

只要把各个任务名称添加到命令行:

E:\java\tools\gradle\demo>gradle TH tasks

> Configure project :
print hello

> Task :tasks
省略其他信息

冒号后面显示任务名称。

在构建过程中任务不会重复执行。

七、命令行选项

命令行选项,例如:--help、-h、-?,能够展示全部命令行选项:

E:\java\tools\gradle\demo>gradle --help

USAGE: gradle [option...] [task...]

-?, -h, --help                     Shows this help message.
-a, --no-rebuild                   Do not rebuild project dependencies.
-b, --build-file                   Specify the build file. (deprecated)
--build-cache                      Enables the Gradle build cache. Gradle will try to reuse outputs from previous builds.
-c, --settings-file                Specify the settings file. (deprecated)
--configuration-cache              Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds. [incubating]
--configuration-cache-problems     Configures how the configuration cache handles problems (fail or warn). Defaults to fail. [incubating]
--configure-on-demand              Configure necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds. [incubating]
--console                          Specifies which type of console output to generate. Values are 'plain', 'auto' (default), 'rich' or 'verbose'.
--continue                         Continue task execution after a task failure.
-D, --system-prop                  Set system property of the JVM (e.g. -Dmyprop=myvalue).
-d, --debug                        Log in debug mode (includes normal stacktrace).
--daemon                           Uses the Gradle Daemon to run the build. Starts the Daemon if not running.
--export-keys                      Exports the public keys used for dependency verification.
-F, --dependency-verification      Configures the dependency verification mode (strict, lenient or off)
--foreground                       Starts the Gradle Daemon in the foreground.
-g, --gradle-user-home             Specifies the gradle user home directory.
-I, --init-script                  Specify an initialization script.
-i, --info                         Set log level to info.
--include-build                    Include the specified build in the composite.
-M, --write-verification-metadata  Generates checksums for dependencies used in the project (comma-separated list)
-m, --dry-run                      Run the builds with all task actions disabled.
--max-workers                      Configure the number of concurrent workers Gradle is allowed to use.
--no-build-cache                   Disables the Gradle build cache.
--no-configuration-cache           Disables the configuration cache. [incubating]
--no-configure-on-demand           Disables the use of configuration on demand. [incubating]
--no-daemon                        Do not use the Gradle daemon to run the build. Useful occasionally if you have configured Gradle to always run with the daemon by default.
--no-parallel                      Disables parallel execution to build projects.
--no-scan                          Disables the creation of a build scan. For more information about build scans, please visit https://gradle.com/build-scans.
--no-watch-fs                      Disables watching the file system.
--offline                          Execute the build without accessing network resources.
-P, --project-prop                 Set project property for the build script (e.g. -Pmyprop=myvalue).
-p, --project-dir                  Specifies the start directory for Gradle. Defaults to current directory.
--parallel                         Build projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.
--priority                         Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Values are 'normal' (default) or 'low'
--profile                          Profile build execution time and generates a report in the <build_dir>/reports/profile directory.
--project-cache-dir                Specify the project-specific cache directory. Defaults to .gradle in the root project directory.
-q, --quiet                        Log errors only.
--refresh-dependencies             Refresh the state of dependencies.
--refresh-keys                     Refresh the public keys used for dependency verification.
--rerun-tasks                      Ignore previously cached task results.
-S, --full-stacktrace              Print out the full (very verbose) stacktrace for all exceptions.
-s, --stacktrace                   Print out the stacktrace for all exceptions.
--scan                             Creates a build scan. Gradle will emit a warning if the build scan plugin has not been applied. (https://gradle.com/build-scans)
--status                           Shows status of running and recently stopped Gradle Daemon(s).
--stop                             Stops the Gradle Daemon if it is running.
-t, --continuous                   Enables continuous build. Gradle does not exit and will re-execute tasks when task file inputs change.
--update-locks                     Perform a partial update of the dependency lock, letting passed in module notations change version. [incubating]
-v, --version                      Print version info.
-w, --warn                         Set log level to warn.
--warning-mode                     Specifies which mode of warnings to generate. Values are 'all', 'fail', 'summary'(default) or 'none'
--watch-fs                         Enables watching the file system for changes, allowing data about the file system to be re-used for the next build.
--write-locks                      Persists dependency resolution for locked configurations, ignoring existing locking information if it exists
-x, --exclude-task                 Specify a task to be excluded from execution.

1、日志选项(控制输出量)

-q, --quiet                        Log errors only.

-d, --debug        Log in debug mode (includes normal stacktrace).少用

-i, --info             Set log level to info.用于理解构建步骤

下面两个选项能与其他选项一起使用

-s, --stacktrace                  Print out the stacktrace for all exceptions.

-S, --full-stacktrace            Print out the full (very verbose) stacktrace for all exceptions.

2、执行其他文件夹下的其他名字的构建文件

默认情况下,gradle命令执行当前文件夹下的build.gradle文件。

①执行其他文件夹的build.gradle文件

假如当前文件夹如下图:

这时我们想执行demo2中的构建文件怎么办?

使用-p, --project-dir                  Specifies the start directory for Gradle. Defaults to current directory.

具体如下:

E:\java\tools\gradle\demo>cd ..

E:\java\tools\gradle>gradle --project-dir demo2 -q hello2
print hello2

 ②执行其他名字的构建文件

假如要执行下图的构建文件:

E:\java\tools\gradle\demo>gradle --build-file aa.bb -q TasknameHello
print hello

3、运行任务但不真正执行

-m, --dry-run                      Run the builds with all task actions disabled.

E:\java\tools\gradle\demo>gradle -m TH tasks

> Configure project :
print hello
:TasknameHello SKIPPED
:tasks SKIPPED

BUILD SUCCESSFUL in 2s

目的是观察任务。

gradle在执行任务之前创建一个有向非循环图,保证了按依赖顺序执行任务和任务只执行一次。

4、更快得构建(Gradle daemon) 

每次我们调用gradle命令时,就会启动新的jvm,然后载入Gradle类和库,最后执行构建。所以为了更快得构建,希望不用再重复构建之前的步骤,那么加上--daemon选项,就会启动一个新的java进程作为daemon进程,这个进程将会拥有Gradle类和库并驻留内存。

在我们这个版本的Gradle,默认就会启动daemon进程,如下:

E:\java\tools\gradle\demo>gradle TH
Starting a Gradle Daemon, 6 stopped Daemons could not be reused, use --status for details

> Configure project :
print hello

BUILD SUCCESSFUL in 7s

当我们再次执行gradle命令时,还是会启动新的jvm,如下图:

但因为有daemon进程在,所以构建会很快:

E:\java\tools\gradle\demo>gradle TH

> Configure project :
print hello

BUILD SUCCESSFUL in 1s

 之后会自动关闭新的jvm,只剩下daemon进程,如下图:

 daemon进程启动后,我们也可以不用它,如下:

E:\java\tools\gradle\demo>gradle --no-daemon TH
To honour the JVM settings for this build a single-use Daemon process will be forked. See https://docs.gradle.org/7.2/userguide/gradle_daemon.html#sec:disabling_the_daemon.
Daemon will be stopped at the end of the build

> Configure project :
print hello

BUILD SUCCESSFUL in 8s

关闭daemon进程:gradle --stop。

如果操作系统支持别名,那么alias gradleplus=‘gradle --daemon’,那么想用daemon进程时,只要执行gradleplus即可。 

设置属性来使用daemon进程,两种方式:

        命令行   export GRADLE_OPTS="-Dorg.gradle.daemon=true"

        配置文件 在项目根目录创建gradle.properties,输入org.gradle.daemon=true

5、查看构建中某些步骤、任务所花时间(--profile) 

E:\java\tools\gradle\demo>gradle --profile TH
Starting a Gradle Daemon (subsequent builds will be faster)

> Configure project :
print hello

BUILD SUCCESSFUL in 19s

See the profiling report at: file:///E:/java/tools/gradle/demo/build/reports/profile/profile-2022-06-12-15-32-38.html
A fine-grained performance profile is available: use the --scan option.

查看build/reports/profile/profile-2022-06-12-15-32-38.html:

 6、离线模式使用gradle(--offline)

如果所需资源都已经准备好,可以使用离线模式。

八、可视化gradle

--gui 但7.2版本没有这个命令行选项

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值