Gradle 自动化构建开源工具

这篇具有很好参考价值的文章主要介绍了Gradle 自动化构建开源工具。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

写在前面

Gradle是一个基于Apache Ant和Apache Maven概念的项目自动化构建开源工具。
面向Java应用为主。当前其支持的语言C++、Java、Groovy、Kotlin、Scala和Swift,计划未来将支持更多的语言。

1、下载与安装(windows)

1、gradle官网下载:https://gradle.org/releases/

Gradle 自动化构建开源工具
2、解压下载Gradle包,配置环境变量
新建系统环境 GRADLE_HOME,值为gradle解压后的目录
找到path变量,后面添加 %GRADLE_HOME%\bin
3、打开cmd,输入gradle -v ,测试是否配置完成

1.1、idea中配置gradle

在IDEA中创建Gradle项目时,会自动生成gradle文件夹,其中就包括 gradle-wrapper.properties ,IDEA默认使用gradle wrapper来创建项目,所以无需安装gradle也可以正常运行。

下面是配置gradle的仓库
Gradle 自动化构建开源工具

2、基础知识(Gradle 6.9为例)

1、Projects 和 tasks
任何一个 Gradle 构建都是由一个或多个 projects 组成。一个projects 由多个project构成,每个 project 都由多个 tasks 组成。每个 task 都代表了构建执行过程中的一个原子性操作。

2、Gradle 脚本采用 Groovy 书写
脚本示例:build.gradle

task hello {
    doLast {
        println 'Hello world!'
    }
}

在该文件目录下执行:gradle -q hello​

以上代码可简写为

task hello {
    println 'Hello world!'
}

<<在Gradle4.x中被弃用,在Gradle 5.0中被移除。
弃用以前写法:

task hello << {
    println 'Hello world!'
}

2.1、Gradle 脚本语法

2.1.1、dependsOn

dependsOn 指定依赖关系

task hello {
    println 'Hello world!'
}
task intro(dependsOn: hello) {
    println "I'm Gradle"
}

延迟依赖:依赖在定义之前使用,该依赖会在后面执行

task taskX(dependsOn: 'taskY') {
    println 'taskX'
}
task taskY {
    println 'taskY'
}

运行结果

 \> gradle -q taskX
taskY
taskX
2.1.2、创建动态任务

Gradle 自动化构建开源工具

\> gradle -q task1
I'm task number 1
2.1.3、增加任务行为

为已存在的任务增加行为。

4.times { counter ->
    task "task$counter" {
        println "I'm task number $counter"
    }
}
task0.dependsOn task2, task3

为任务增加多个行为

task hello {
    println 'Hello Earth'
}
hello.doFirst {
    println 'Hello Venus'
}
hello.doLast {
    println 'Hello Mars'
}
hello {
    println 'Hello Jupiter'
}
2.1.4、参数

$hello.name 可以调用任务hello的名字

task hello {
    println 'Hello world!'
}
hello.doLast {
    println "Greetings from the $hello.name task."
}

新增一个叫做 myProperty 的属性,用 ext.myProperty 的方式给他一个初始值。

task myTask {
    ext.myProperty = "myValue"
}

task printTaskProperties {
    println myTask.myProperty
}
2.1.5、Ant 任务

对 Ant 任务进行了的整合

task loadfile {
    def files = file('../antLoadfileResources').listFiles().sort()
    files.each { File file ->
        if (file.isFile()) {
            ant.loadfile(srcFile: file, property: file.name)
            println " *** $file.name ***"
            println "${ant.properties[file.name]}"
        }
    }
}
2.1.6、方法

写一个方法fileList()

task checksum {
    fileList('../antLoadfileResources').each {File file ->
        ant.checksum(file: file, property: "cs_$file.name")
        println "$file.name Checksum: ${ant.properties["cs_$file.name"]}"
    }
}
task loadfile {
    fileList('../antLoadfileResources').each {File file ->
        ant.loadfile(srcFile: file, property: file.name)
        println "I'm fond of $file.name"
    }
}
File[] fileList(String dir) {
    file(dir).listFiles({file -> file.isFile() } as FileFilter).sort()
}
2.1.7、默认任务

定义默认任务

defaultTasks 'clean', 'run'
task clean {
    println '默认任务1'
}
task run {
    println '默认任务2'
}
task other {
    println "这个不是默认任务"
}

执行

\> gradle -q
默认任务1
默认任务2
2.1.6、依赖任务的不同输出

依赖任务的不同输出

task distribution << {
    println "We build the zip with version=$version"
}
task release(dependsOn: 'distribution') << {
    println 'We release now'
}
gradle.taskGraph.whenReady {taskGraph ->
    if (taskGraph.hasTask(release)) {
        version = '1.0'
    } else {
        version = '1.0-SNAPSHOT'
    }
}

输出

\> gradle -q distribution
We build the zip with version=1.0-SNAPSHOT

\> gradle -q release
We build the zip with version=1.0
We release now

3、java项目中使用

3.1、在已有项目中构建gradle

在项目目录下:gradle init

Gradle 自动化构建开源工具
构建完成会生成相关文件

Gradle 自动化构建开源工具

3.2、在新建项目时构建gradle(idea)

在idea中新建Gradle项目

Gradle 自动化构建开源工具
新建一个项目gradleDemo1,如下是项目目录结构

Gradle 自动化构建开源工具

3.3、gradle项目目录结构

├─.gradle                           
├─.idea
├─gradle                            // 为包装文件生成的文件夹
│  └─wrapper
│    ├── gradle-wrapper.jar
│    └── gradle-wrapper.properties
├── gradlew                          // Gradle 包装器启动脚本
├── gradlew.bat                      // Gradle 包装器启动脚本
├── settings.gradle                  // 用于定义构建名称和子项目的设置文件
├── build.gradle                     // gradle 配置内容
└─src                                // 项目代码
    ├─main
    │  ├─java
    │  └─resources
    └─test
        ├─java
        └─resources

3.4、build.gradle

Gradle 自动化构建开源工具

3.4.1、plugins

plugins 中配置的是gradle脚本使用到的插件。如果使用的是核心插件如 ‘java’无需指定版本,使用的是“社区插件”则必须指定version。

plugins {
    id 'java'
    id 'application'
    id 'org.springframework.boot' version '2.3.4.RELEASE'
}
3.4.2、repositories

repositories 配置各种仓库示例

repositories {
    mavenLocal()
    maven { url 'http://192.168.1.1:80/content/groups/public' }
    maven { url 'http://192.168.1.1:80/content/groups/public-snapshots' }
    mavenCentral()
}
3.4.3、dependencies

dependencies 项目依赖项示例

dependencies {
    //单个依赖
    implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.73'
    //单个依赖简写
    implementation 'com.alibaba:fastjson:1.2.73'
    //多个依赖
    implementation 'com.alibaba:fastjson:1.2.73', 'log4j:log4j:1.2.17'
    //闭包依赖,为了添加额外配置
    implementation("org.mybatis:mybatis:3.5.6"){
        exclude group :"org.springframework",module:"spring"
        exclude group :"org.javassist",module:"javassist"
        exclude group :"org.jboss.netty",module:"netty"
    }
    //双引号方式使用变量,在ext中声明或 def 关键字声明变量 lombok_version=具体版本
    annotationProcessor "org.projectlombok:lombok:$lombok_version"
    compileOnly "org.projectlombok:lombok:${lombok_version}"
}
3.4.4、configurations

configurations 配置全局排除依赖示例

configurations {
    all{
        exclude group :"org.springframework.boot",module:"spring-boot-starter-logging"
    }
    //编译期排除
    //compile.exclude module: 'spring-boot-starter-logging'
    //在构建过程中排除
    //all*.exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
}
//简写
configurations.all*.exclude module: "spring-boot-starter-logging"
3.4.5、buildscript

buildscript 中声明的是gradle脚本自身需要使用的资源。可以声明包括变量、任务、依赖项、第三方插件、maven仓库地址等。gradle在执行脚本时会优先执行该代码块中的内容,而后执行其它脚本。

buildscript {
  //变量
  ext {
    spring_boot_version = '2.3.4.RELEASE'
    spring_dependency_management_version = '1.0.10.RELEASE'
  }
  
  //maven仓库
  repositories {
    mavenLocal()
    maven { url 'http://192.168.1.1:80/content/groups/public' }
    maven { url 'http://192.168.1.1:80/content/groups/public-snapshots' }
    mavenCentral()
  }
  
  //依赖项
  dependencies {
    classpath "io.spring.gradle:dependency-management-plugin:${spring_dependency_management_version}"
    classpath "org.springframework.boot:spring-boot-gradle-plugin:${spring_boot_version}"
  }
  
  //任务
  task myTask(){
  	//处理任务
  }
3.4.6、依赖版本管理

在gradle官方文档中明确指出,如果想使用依赖关系管理,那就需要使用的gradle版本大于4.4。

方式一,使用插件:

plugins {
    id 'java'
    //指定版本
    id 'org.springframework.boot' version "2.3.4.RELEASE"
    //配置依赖管理插件,自定义托管版本
    id 'io.spring.dependency-management' version "1.0.10.RELEASE"
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    testImplementation "org.springframework.boot:spring-boot-starter-test"
}

方式二,使用插件,自动追加版本

plugins {
    id 'java'
    //指定版本
    id 'org.springframework.boot' version "2.3.4.RELEASE"
}

//应用依赖管理插件,自动给插件追加版本号
apply plugin: "io.spring.dependency-management"

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    testImplementation "org.springframework.boot:spring-boot-starter-test"
}

使用 BOM 方式管理 spring-cloud依赖版本

plugins {
    id 'java'
    id 'org.springframework.boot' version "2.3.4.RELEASE"
    id 'io.spring.dependency-management' version "1.0.10.RELEASE"
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation "org.springframework.cloud:spring-cloud-starter-config"
	implementation "org.springframework.cloud:spring-cloud-starter-openfeign"
}

dependencyManagement {
    imports {
    	mavenBom "org.springframework.cloud:spring-cloud-dependencies:${spring_cloud_version}"
    }
}
3.4.7、乱码与测试编译

编译乱码处理

//在 build.gradle 增加以下配置
tasks.withType(JavaCompile) {
    options.encoding = 'UTF-8'
}

跳过测试编译

//在 build.gradle 增加以下配置
gradle.taskGraph.whenReady {
    tasks.each { task ->
        if (task.name.contains("test")) {
            task.enabled = false
        }
    }
}
3.4.8、发布私服配置
// 1.私服账号密码
buildscript {
    ext {
        nexusUsername = 'admin'
        nexusPassword = '12345'
    }
}
// 2.配置分组,版本号
group 'com.alone.demo'
version '0.0.1-SNAPSHOT'
// 3.配置maven插件
plugins {
    id 'maven'
}

//发布私服,包名为文件 settings.gradle 中 rootProject.name 配置的名称,版本为上文配置的 verison 版本号
uploadArchives {
    repositories {
        mavenDeployer {
        	//这里配置自己的私服地址
            repository(url: "http://192.168.1.1:80/content/repositories/releases/") {
                authentication(userName: nexusUsername, password: nexusPassword)
            }
            //这里配置自己的私服地址
            snapshotRepository(url: "http://192.168.1.1:80/content/repositories/snapshots/") {
                authentication(userName: nexusUsername, password: nexusPassword)
            }
        }
    }
}

执行发布

gradle uploadArchives

发布本地

// 1.配置分组,版本号
group 'com.alone.demo'
version '0.0.1-SNAPSHOT'
// 3.配置maven插件
plugins {
    id 'maven-publish'
}

//发布本地,包名为文件 settings.gradle 中 rootProject.name 配置的名称,版本为上文配置的 verison 版本号
publishing {
    publications {
        maven(MavenPublication) {
            from(components.java)
        }
    }
}
3.4.9、依赖冲突

1.通过配置全局排除冲突包(全局封杀)

//方式一
configurations {
    all{
        exclude group :"org.springframework.boot",module:"spring-boot-starter-logging"
    }
}

//方式二 简写
configurations.all*.exclude module: "spring-boot-starter-logging"

2.诊断出具体依赖项冲突可以排除具体包

dependencies {
    implementation("org.mybatis:mybatis:3.5.6"){
        exclude group :"org.springframework",module:"spring"
        exclude group :"org.jboss.netty",module:"netty"
    }
}

3.强制指定版本策略,即在发生冲突时使用指定的版本

//冲突失败策略设置
configurations.all {
    resolutionStrategy {  failOnVersionConflict() }
}
//强制指定版本策略设置
dependencies {
	//方式一 闭包
    implementation ("io.netty:netty-all:4.0.44.Final"){
        force true
    }
    //方式二 简写
    implementation group: 'io.netty', name: 'netty-all', version: '4.0.44.Final', force: true
}

4.在平时使用动态依赖来减小发生版本冲突的几率

dependencies {
    //方式一:指定某个版本以上,减小发生版本冲突的几率。如以下依赖选择 3 以上任意一个版本
    implementation 'cn.afterturn:easypoi-base:3.+'
    // 方式二:选择最新的版本
    implementation 'cn.afterturn:easypoi-base:latest.integration'
}

3.5、相关指令

gradle clean              // 清理
gradle clean build        // 构建打包
gradle dependencies       // 查看依赖
gradle dependencies -configuration compile        // 查看编译时依赖
gradle clean build -x test                        // 编译时跳过测试,使用 -x,-x 参数用来排除不需要执行的任务

idea可以在界面上操作

Gradle 自动化构建开源工具文章来源地址https://www.toymoban.com/news/detail-421579.html

到了这里,关于Gradle 自动化构建开源工具的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • [Linux 基础] make、Makefile自动化构建工具

    make是一个命令,Makefile是一个在当前目录下存在的一个具有特定格式的文本文件。 在VS编译器中,我们在编译执行代码的时候ctrl+f5就可以了,而在linux中我们需要使用gcc/g++ 配合选项并需要正确的格式才可以完成编译,这样是比较麻烦的,我们make与Makefile可以实现自动化构建

    2024年02月06日
    浏览(30)
  • Linux:项目自动化构建工具——make/Makefile

    前言: 本章主要内容有认识与学习 Linux 环境下如何使用项目自动化构建工具—— make/makefile 。 当我们编写一个较大的软件项目时,通常需要将多个源文件编译成可执行程序或库文件。为了简化这个过程,我们可以使用 make 工具和 Makefile 文件。 Makefile 文件可以帮助我们 自动

    2024年02月13日
    浏览(32)
  • 【Linux】项目自动化构建工具make/makefile

    🏖️作者:@malloc不出对象 ⛺专栏:Linux的学习之路 👦个人简介:一名双非本科院校大二在读的科班编程菜鸟,努力编程只为赶上各位大佬的步伐🙈🙈 本篇文章我们将要讲解的是项目自动化构建工具make与makefile。 一、make/makefile的背景 会不会写makefile,从一个侧面说明了一

    2024年02月03日
    浏览(43)
  • 【Linux】自动化构建工具-make/Makefile详解

     前言 大家好吖,欢迎来到 YY 滴 Linux系列 ,热烈欢迎! 本章主要内容面向接触过Linux的老铁,主要内容含 欢迎订阅 YY 滴Linux专栏!更多干货持续更新!以下是传送门!  订阅专栏阅读:YY的《Linux》系列 ❀❀❀❀❀ 【Linux系列-P1】 Linux环境的搭建 【Linux系列-P2】Linux的基本知

    2024年02月16日
    浏览(28)
  • 【Linux】项目自动化构建工具 —— make/Makefile

    前言: 在上一期的博文中,我们对 Linux 下的编译器 - gcc/g++的使用进行了详细的讲解,今天我将给大家讲解的是关于  【Linux】项目自动化构建工具 —— make/Makefile  的详细使用教程!! 本文目录 (一)前情摘要 (二)背景介绍 1、Makefile 的基本认识 2、make 的基本认识 3、

    2023年04月19日
    浏览(47)
  • 【Linux】自动化构建工具make和Makefile

           🔥🔥 欢迎来到小林的博客!!       🛰️博客主页:✈️小林爱敲代码       🛰️社区 : 进步学堂       🛰️专栏 : Linux之路       🛰️欢迎关注:👍点赞🙌收藏✍️留言 在一个工程中的源文件不计数,其按类型、功能、模

    2023年04月18日
    浏览(29)
  • 【Linux】项目自动化构建工具 - make/Makefile

    会不会写makefile,从侧面说明了一个人是否具备完成大型工程的能力。 一个工程中的源文件不计数,其按类型、功能、模块分别放在若干个目录中,makefile定义了一系列的规则来指定,哪些文件需要先编译,哪些文件需要后编译,哪些文件需要重新编译,甚至于进行更复杂的

    2024年02月04日
    浏览(38)
  • 【Linux】项目自动化构建工具-make/Makefile

    会不会写makefile,从一个侧面说明了一个人是否具备完成大型工程的能力 一个工程中的源文件不计数,其按类型、功能、模块分别放在若干个目录中,makefile定义了一系列的规则来指定,哪些文件需要先编译,哪些文件需要后编译,哪些文件需要重新编译,甚至于进行更复杂

    2023年04月09日
    浏览(36)
  • 【Linux】快速上手自动化构建工具make/makefile

    👀 樊梓慕: 个人主页  🎥 个人专栏: 《C语言》《数据结构》《蓝桥杯试题》《LeetCode刷题笔记》《实训项目》《C++》《Linux》 🌝 每一个不曾起舞的日子,都是对生命的辜负 目录 前言 1.什么是make / makefile 2.如何使用make / makefile (1)我们来看makefile如何写? (2)如何与

    2024年02月05日
    浏览(31)
  • [Linux 基础] make、Makefile自动化构建代码工具

    make是一个命令,Makefile是一个在当前目录下存在的一个具有特定格式的文本文件。 在VS编译器中,我们在编译执行代码的时候ctrl+f5就可以了,而在linux中我们需要使用gcc/g++ 配合选项并需要正确的格式才可以完成编译,这样是比较麻烦的,我们make与Makefile可以实现自动化构建

    2024年02月08日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包