写在前面
本篇,我们来探讨如何创建一个新的Gradle应用,同时讲解内部的相关细节内容。
项目初始化
以windows系统为例
1.创建初始化项目目录
E:\SunLineProjects>mkdir basic-demo
E:\SunLineProjects>cd basic-demo
项目目录创建成功
2.gradle初始化
E:\SunLineProjects\basic-demo>gradle init
选择生成的类型,本次演示应用的创建,因此选择2
选择内部实现语言,此处选择java ,选择3
选择合适的构建脚本格式、测试框架
“BUILD SUCCESSFUL” 代表成功
注意:如果初始化过程存在错误,一般需要检查gradle的安装、本地java环境
3.项目目录介绍
按照构建脚本不同,略有不同
1 |
本项目的Gradle 构建脚本 |
2 |
Gradle Wrapper 可执行jar |
3 |
Gradle Wrapper 配置文件 |
4 |
Gradle Wrapper Unix-based 系统脚本 |
5 |
Gradle Wrapper Windows 脚本 |
6 |
用于配置Gradle 配置构建工具的脚本配置 |
后续有详细文章描述Wrapper
4.创建执行任务
Gradle提供了用于通过Groovy或基于Kotlin的DSL创建和配置任务的API。一个项目包括一组任务,每个任务都执行一些基本操作。
Gradle带有一个任务库,您可以在自己的项目中对其进行配置。例如,有一个称为“复制”的核心类型,它将文件从一个位置复制到另一位置。复制任务非常有用(有关详细信息,请参见文档),但是在这里,让我们再次简化它。执行以下步骤:
–创建一个名为src的目录。
–在src目录中添加一个名为myfile.txt的文件。内容是任意的(甚至可以为空),但为方便起见,请添加单行Hello,World!对此。
在build.gradle文件中,在构建文件中定义一个名为Copy类型的副本的任务(请注意大写字母),该任务将src目录复制到一个名为dest的新目录中。(您不必创建目标目录,任务将为您完成。)
因为我们之前选择的应用,就会创建一个Gradle的应用,所以,我们可以直接尝试创建一个文件,来尝试Copy任务
以Groovy为例
task copy(type: Copy, group: "Custom", description: "Copies sources to the dest directory") {
from "src/main/resources"
into "dest"
}
将resources目录下所有内容,转移到dest目录下
创建一个文本文件,打开终端应用,windows的cmd命令框
E:\SunLineProjects\basic-demo>gradlew copy
BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed
完成资源的copy任务
5.插件应用
Gradle包括一系列插件,并且在Gradle插件门户网站上可以找到许多很多插件。发行版随附的插件中都称为base插件。核心类型结合起来称为Zip插件,可以使用配置的名称和位置创建项目的zip存档。
使用plugins语法将base插件添加到您的构建脚本文件中。确保在文件顶部添加plugins {}块。
添加如下代码配置
plugins {
id "base"
}
... rest of the build file ...
之后,build.gradle代码如下:
plugins {
// Apply the java plugin to add support for Java
id 'java'
// Apply the application plugin to add support for building a CLI application.
id 'application'
id 'base'
}
增加一个任务创建zip
task zip(type: Zip, group: "Archive", description: "Archives sources in a zip file") {
from "src/main/resources"
archiveFileName = "basic-demo-1.0.zip"
}
执行任务,代码如下
E:\SunLineProjects\basic-demo>gradlew zip
BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed
效果如下,会创建一个压缩包
6.其他使用
安装完base插件后
–通过tasks命令,简单获取所有可执行任务
E:\SunLineProjects\basic-demo>gradlew tasks
> Task :tasks
------------------------------------------------------------
Tasks runnable from root project
------------------------------------------------------------
Application tasks
-----------------
run - Runs this project as a JVM application
Archive tasks
-------------
zip - Archives sources in a zip file
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.
Custom tasks
------------
copy - Copies sources to the dest directory
Distribution tasks
------------------
assembleDist - Assembles the main distributions
distTar - Bundles the project as a distribution.
distZip - Bundles the project as a distribution.
installDist - Installs the project as a distribution as-is.
Documentation tasks
-------------------
javadoc - Generates Javadoc API documentation for the main source code.
Help tasks
----------
buildEnvironment - Displays all buildscript dependencies declared in root project 'basic-demo'.
components - Displays the components produced by root project 'basic-demo'. [incubating]
dependencies - Displays all dependencies declared in root project 'basic-demo'.
dependencyInsight - Displays the insight into a specific dependency in root project 'basic-demo'.
dependentComponents - Displays the dependent components of components in root project 'basic-demo'. [incubating]
help - Displays a help message.
model - Displays the configuration model of root project 'basic-demo'. [incubating]
outgoingVariants - Displays the outgoing variants of root project 'basic-demo'.
projects - Displays the sub-projects of root project 'basic-demo'.
properties - Displays the properties of root project 'basic-demo'.
tasks - Displays the tasks runnable from root project 'basic-demo'.
Verification tasks
------------------
check - Runs all checks.
test - Runs the unit tests.
Rules
-----
Pattern: clean: Cleans the output files of a task.
Pattern: build: Assembles the artifacts of a configuration.
Pattern: upload: Assembles and uploads the artifacts belonging to a configuration.
To see all tasks and more detail, run gradlew tasks --all
To see more detail about a task, run gradlew help --task
BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed
–分析扫描应用
Gradle还提供了基于构建的丰富的基于Web的视图,称为构建扫描。
通过使用--scan选项或将构建扫描插件显式应用到您的项目,可以在scans.gradle.com免费创建构建扫描。将构建扫描发布到scans.gradle.com会将这些数据传输到Gradle的服务器。要将数据保存在自己的服务器上,需要Gradle Enterprise。
E:\SunLineProjects\basic-demo>gradlew build --scan
> Task :compileJava FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':compileJava'.
> Could not resolve all files for configuration ':compileClasspath'.
> Could not download guava-29.0-jre.jar (com.google.guava:guava:29.0-jre)
> Could not get resource 'https://jcenter.bintray.com/com/google/guava/guava/29.0-jre/guava-29.0-jre.jar'.
> Could not GET 'https://d29vzk4ow07wi7.cloudfront.net/b22c5fb66d61e7b9522531d04b2f915b5158e80aa0b40ee7282c8bfb07b0da25?response-content-disposition=attachment%3Bfilename%3D%22guava-29.0-jre.jar%22&Policy=eyJTdGF0ZW1lbnQiOiBbeyJSZXNvdXJjZSI6Imh0dHAqOi8vZDI5dnprNG93MDd3aTcuY2xvdWRmcm9udC5uZXQvYjIyYzVmYjY2ZDYxZTdiOTUyMjUzMWQwNGIyZjkxNWI1MTU4ZTgwYWEwYjQwZWU3MjgyYzhiZmIwN2IwZGEyNT9yZXNwb25zZS1jb250ZW50LWRpc3Bvc2l0aW9uPWF0dGFjaG1lbnQlM0JmaWxlbmFtZSUzRCUyMmd1YXZhLTI5LjAtanJlLmphciUyMiIsIkNvbmRpdGlvbiI6eyJEYXRlTGVzc1RoYW4iOnsiQVdTOkVwb2NoVGltZSI6MTU5MzQ0MDQ3OX0sIklwQWRkcmVzcyI6eyJBV1M6U291cmNlSXAiOiIwLjAuMC4wLzAifX19XX0_&Signature=FjWaVYHZ4wXIhvUI54lPbEH0Yeoisoy~bKWarfjpyJxwLHUG7CsHMuZhB4Rlb6IQe1m~XJu4Jdt0hxVkxhanaVV9bueXcO-gbuzsVGlOEZDy5pO2NfZpQv-vXSyOiJ0TdOieyt~O3dcD8hjR3Nxbn65-FQAtv95UaNBWKeyt7dSQ9Z10QpFuLEMNPLZpnkSTBNxQvutAuuI90iXVR5f6pjysAII8O8v672IX42SlLVGBTZVbWTpi~9DJN~WJtxfyPHz2P958HHibRS0kSMGSXoUCrIzs0LNb-K-oKuRiM99ZjiVaWb3~R24EjFS5Awa5m3uwdJz4Mq8Vo0boyQdyLA__&Key-Pair-Id=APKAIFKFWOMXM2UMTSFA'.
> d29vzk4ow07wi7.cloudfront.net
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 19s
1 actionable task: 1 executed
Publishing a build scan to scans.gradle.com requires accepting the Gradle Terms of Service defined at https://gradle.comGradle Terms of Service accepted.
Publishing build scan... files of :compileClasspath
https://gradle.com/s/jg3pbff6v74ok
依赖下载失败,构建失败,但是会把结果push到网站 https://gradle.com/s/jg3pbff6v74ok
–有用的属性配置
通过 gradlew properties 可以查询所有的可配置属性
E:\SunLineProjects\basic-demo>gradlew properties
> Task :properties
------------------------------------------------------------
Root project
------------------------------------------------------------
allprojects: [root project 'basic-demo']
ant: org.gradle.api.internal.project.DefaultAntBuilder@77ef8899
antBuilderFactory: org.gradle.api.internal.project.DefaultAntBuilderFactory@2d318889
application: extension 'application'
applicationDefaultJvmArgs: []
applicationDistribution: org.gradle.api.internal.file.copy.DefaultCopySpec_Decorated@44daed18
applicationName: basic-demo
archivesBaseName: basic-demo
artifacts: org.gradle.api.internal.artifacts.dsl.DefaultArtifactHandler_Decorated@4408d2f7
asDynamicObject: DynamicObject for root project 'basic-demo'
autoTargetJvmDisabled: false
baseClassLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@4fa821af
buildDir: E:\SunLineProjects\basic-demo\build
buildFile: E:\SunLineProjects\basic-demo\build.gradle
buildPath: :
buildScriptSource: org.gradle.groovy.scripts.TextResourceScriptSource@6e7c8d13
buildscript: org.gradle.api.internal.initialization.DefaultScriptHandler@7ddd1fe9
childProjects: {}
class: class org.gradle.api.internal.project.DefaultProject_Decorated
classLoaderScope: org.gradle.api.internal.initialization.DefaultClassLoaderScope@7fc0e5cf
components: SoftwareComponentInternal set
configurationActions: org.gradle.configuration.project.DefaultProjectConfigurationActionContainer@71eb06c1
configurationTargetIdentifier: org.gradle.configuration.ConfigurationTargetIdentifier$1@7b7509fa
configurations: configuration container
convention: org.gradle.internal.extensibility.DefaultConvention@6ec2632a
copy: task ':copy'
defaultArtifacts: extension 'defaultArtifacts'
defaultTasks: []
deferredProjectConfiguration: org.gradle.api.internal.project.DeferredProjectConfiguration@16d41da0
dependencies: org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@3f20dcb5
dependencyLocking: org.gradle.internal.locking.DefaultDependencyLockingHandler_Decorated@6c492872
depth: 0
description: null
displayName: root project 'basic-demo'
distributions: Distribution container
distsDir: E:\SunLineProjects\basic-demo\build\distributions
distsDirName: distributions
distsDirectory: property(org.gradle.api.file.Directory, map(org.gradle.api.file.Directory property(org.gradle.api.file.Directory, fixed(class org.gradle.api.internal.file.DefaultFilePropertyFactory$FixedDirectory, E:\SunLineProjects\basic-demo\build)) org.gradle.api.internal.file.DefaultFilePropertyFactory$PathToDirectoryTransformer@11efdde2))
docsDir: E:\SunLineProjects\basic-demo\build\docs
docsDirName: docs
executableDir: bin
ext: org.gradle.internal.extensibility.DefaultExtraPropertiesExtension@27e0eb62
extensions: org.gradle.internal.extensibility.DefaultConvention@6ec2632a
fileOperations: org.gradle.api.internal.file.DefaultFileOperations@1e9c4e5f
fileResolver: org.gradle.api.internal.file.BaseDirFileResolver@3b33ff46
gradle: build 'basic-demo'
group:
identityPath: :
inheritedScope: org.gradle.internal.extensibility.ExtensibleDynamicObject$InheritedDynamicObject@54dc250f
java: extension 'java'
javaInstalls: org.gradle.jvm.toolchain.internal.DefaultJavaInstallationRegistry@74c76f0d
layout: org.gradle.api.internal.file.DefaultProjectLayout@8d5297c
libsDir: E:\SunLineProjects\basic-demo\build\libs
libsDirName: libs
libsDirectory: property(org.gradle.api.file.Directory, map(org.gradle.api.file.Directory property(org.gradle.api.file.Directory, fixed(class org.gradle.api.internal.file.DefaultFilePropertyFactory$FixedDirectory, E:\SunLineProjects\basic-demo\build)) org.gradle.api.internal.file.DefaultFilePropertyFactory$PathToDirectoryTransformer@2c382eef))
listenerBuildOperationDecorator: org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator@1979823a
logger: org.gradle.internal.logging.slf4j.OutputEventListenerBackedLogger@7901220f
logging: org.gradle.internal.logging.services.DefaultLoggingManager@5609291f
mainClassName: basic.demo.App
model: project :
modelIdentityDisplayName: null
modelRegistry: org.gradle.model.internal.registry.DefaultModelRegistry@7736746b
modelSchemaStore: org.gradle.model.internal.manage.schema.extract.DefaultModelSchemaStore@65985b57
module: org.gradle.api.internal.artifacts.ProjectBackedModule@6635ceb7
mutationState: project :
name: basic-demo
normalization: org.gradle.normalization.internal.DefaultInputNormalizationHandler_Decorated@1a947334
objects: org.gradle.api.internal.model.DefaultObjectFactory@4fa94a0e
parent: null
parentIdentifier: null
path: :
pluginManager: org.gradle.api.internal.plugins.DefaultPluginManager_Decorated@50f7d335
plugins: [org.gradle.api.plugins.HelpTasksPlugin@1426606c, org.gradle.buildinit.plugins.BuildInitPlugin@2d92bc0f, org.gradle.buildinit.plugins.WrapperPlugin@286e6a89, org.gradle.language.base.plugins.LifecycleBasePlugin@46ee6aca, org.gradle.api.plugins.BasePlugin@61ec477b, org.gradle.api.plugins.ReportingBasePlugin@59a6fd8d, org.gradle.api.plugins.JavaBasePlugin@247ee12, org.gradle.api.plugins.JavaPlugin@37ca7caa, org.gradle.api.distribution.plugins.DistributionPlugin@341e22b7, org.gradle.api.plugins.ApplicationPlugin@5a3aeb2c]
processOperations: org.gradle.process.internal.DefaultExecActionFactory$DecoratingExecActionFactory@67b0b907
project: root project 'basic-demo'
projectConfigurator: org.gradle.api.internal.project.BuildOperationCrossProjectConfigurator@37bb677
projectDir: E:\SunLineProjects\basic-demo
projectEvaluationBroadcaster: ProjectEvaluationListener broadcast
projectEvaluator: org.gradle.configuration.project.LifecycleProjectEvaluator@46353735
projectPath: :
projectRegistry: org.gradle.api.internal.project.DefaultProjectRegistry@4b5bc754
properties: {...}
providers: org.gradle.api.internal.provider.DefaultProviderFactory_Decorated@29c127b9
publicType: org.gradle.api.plugins.BasePluginConvention
reporting: extension 'reporting'
reportsDir: E:\SunLineProjects\basic-demo\build\reports
repositories: repository container
resources: org.gradle.api.internal.resources.DefaultResourceHandler@7757e4f8
rootDir: E:\SunLineProjects\basic-demo
rootProject: root project 'basic-demo'
script: false
scriptHandlerFactory: org.gradle.api.internal.initialization.DefaultScriptHandlerFactory@18b4f9b8
scriptPluginFactory: org.gradle.configuration.ScriptPluginFactorySelector@dc0fc9d
serviceRegistryFactory: org.gradle.internal.service.scopes.ProjectScopeServices$$Lambda$452/526579982@5a371303
services: ProjectScopeServices
sourceCompatibility: 1.8
sourceSets: SourceSet container
standardOutputCapture: org.gradle.internal.logging.services.DefaultLoggingManager@5609291f
state: project state 'EXECUTED'
status: integration
subprojects: []
targetCompatibility: 1.8
taskThatOwnsThisObject: null
tasks: task set
testReportDir: E:\SunLineProjects\basic-demo\build\reports\tests
testReportDirName: tests
testResultsDir: E:\SunLineProjects\basic-demo\build\test-results
testResultsDirName: test-results
version: unspecified
zip: task ':zip'
BUILD SUCCESSFUL in 3s
1 actionable task: 1 executed
默认情况下,项目name属性与文件夹名称匹配。您还可以指定groupandversion属性,但目前它们正采用其默认值,如description属性所示。
buildFile属性是构建脚本的标准路径名,默认情况下位于projectDir中。
更改许多属性。例如,您可以尝试将以下行添加到构建脚本文件中,然后重新执行gradle属性。
description = "A trivial Gradle build"
version = "1.0"
总结
本次,我们学习了入门应用的构建,以及相关配置内容,之后我们将开始真正去描述应用中的使用。