gradle构建的项目有build.gradle和settings.gradle文件
- build.gradle - 文件包含项目构建所使用的脚本。
- settings.gradle - 文件将包含必要的一些设置,例如,任务或项目之间的依懒关系等
settings.gradle配置
settings.gradles是模块Module配置文件,大多数setting.gradle的作用是为了配置子模块,
根目录下的setting.gradle脚本文件是针对module的全局配置
settings.gradle用于创建多Project的Gradle项目。Project在IDEA里对应Module模块。
例如配置module名rootProject.name = 'project-root',为指定父模块的名称,
include 'hello' 为指定包含哪些子模块
//平台根
rootProject.name = 'project-root'
//包含子系统以及模块
include ':project-core'
//Hello系统模块的加载
include ':project-hello'
//World系统模块的加载
include ':project-world'
build.gradle的配置(类似于Maven工程中的pom.xml相同)
1.subprojects
1.1 apply plugin:'java' 表示应用java插件添加对java的支持
1.2 apply plngin:'war'表示应用的war插件
1.3 repositories 为指定第三方依赖包仓库的地址,
图中配置的依次为本地仓库,maven私服地址,以及maven中央仓库。
```
//声明在何处查找项目的依赖项
repositories{
mavenCentral()
}
```
repositories是一个仓库,gradle会根据从上到下的顺序依次去仓库中寻找jar.
其中mavenLocal()表示使用本地maven仓库;
mavenCentral()使用maven中心仓库 。
1.4 dependencies是用于声明这个项目依赖于哪些jar
```
dependencies{
testCompile group:'junit','name','version':'4.11'
}
//In this section you declare the dependencies for your production and test code
dependencies {
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.0
// The production code uses the SLF4J logging API at compile time
compile 'org.slf4j:slf4j-api:1.7.21'
// 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'
}
```
测试编译阶段我们依赖junit的jar。其中包括complile(编译时)
runtime(运行时)testCompile(测试编译时)testRuntime(测试运行时)
。
```
repositories{
mavenCentral()
}
```
1.5 sourceCompatibility和targetCompatibility
sourceCompatibility:指定编译.java文件的jdk版本
targetCompatibility:确保.class文件与targetCompatibility
所指定版本或者更新版本的java虚拟机兼容
要求targetCompatibility>=sourceCompatibility
编写代码依赖
在需要依赖的模块上面的build.gradle文件内
,查找到dependencies{}模块。添加以下代码:
compile project(':名称')
在冒号后面输入模块的名称
2.在网络查看Gradle存储库
在哪里查找信息groupId,artifactId和版本?
可以去网站: http://mvnrepository.com ,在首页搜索common-lang3
,然后点击需要的版本号,例如点击3.9,就会出现相对应的信息
Gradle命令介绍
gradle projects 查看工程信息
gradle tasks 查看任务信息
gradle task name 执行task任务
Gradle 工作流程
以multi-project build为例,Gradle工作流程如下:
初始化阶段:
首先解析settings.gradle
Configration阶段:
解析每个Project中的build.gradle,解析过程中并不会执行各个build.gradle中的task。
经过Configration阶段,Project之间及内部Task
之间的关系就确定了。一个 Project 包含很多 Task,
每个 Task 之间有依赖关系。Configuration
会建立一个有向图来描述 Task 之间的依赖关系,
所有Project配置完成后,会有一个回调project
.afterEvaluate,表示所有的模块都已经配置完了。