Java小知识(02)Gradle项目中的build.gradle文件配置解释

一、build.gradle

1.0 Groovy简单语法

1.0.1 声明变量

// 动态类型,千万别记成弱类型!
def var = "123"
// 可以省略 def关键字。这样定义的变量作用域更大
var2 = "123str"

1.0.2 方法和闭包

无参数简单闭包

//  闭包
//  无参数简单闭包
def myClosure = {
    println "闭包输出"
}
// 声明方法
def method(Closure closure) {
    closure()
}
// 将闭包传入方法中
method(myClosure)

如果省略括号,就可以写的飘逸一些就变成gradle中的配置写法那样了。方法名+闭包调用

method{闭包内容}  等价于 method(){闭包} 等价于  method({闭包内容})

参数闭包


//  参数闭包
def myClosure2 = {
    str -> println "闭包输出$str"
}

// 声明方法
def method2(Closure closure) {
    closure("abc")
}

method2(myClosure2)

1.1 文件

// !!!!!注意,别看这花里胡哨的语法,其实都是Groovy的语法。都是省略括号的形式和闭包形式

plugins {
    id 'java' // 使用插件
}

apply plugin: 'war' // 打成war包
 
group 'com.sjx' // 每个jar包都有一个坐标,这是域名。
version '1.0-SNAPSHOT' // 版本

// 兼容版本:1.8
sourceCompatibility = 1.8

// 指定仓库的路径
repositories {
    // 需要配置GRADLE_USER_HOME 这个环境变量。设置为本地maven仓库即可
    mavenLocal() // 使用本地仓库
    mavenCentral() // 默认使用中央仓库
}

/**
 * 每个jar包有三个信息组成group、name、version
 * 可省略括号,可用语法糖形式——域名:项目名:版本号
 */
dependencies {
    compile ('org.springframework.boot:spring-boot-starter-web:2.1.4.RELEASE')
    compile 'org.springframework.boot:spring-boot-starter-web:2.1.4.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

1.2 gradle作用

使用Gradl构建项目,管理jar包。像maven一样。在gradle中,配置都是在 build.gradle文件中配置的。比如我们需要Spring的jar包。可以在dependencies方法中传入闭包——在闭包中调用complie方法并传入jar包坐标:

dependencies {
    compile ('org.springframework.boot:spring-boot-starter-web:2.1.4.RELEASE')
    compile 'org.springframework.boot:spring-boot-starter-web:2.1.4.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}
发布了17 篇原创文章 · 获赞 7 · 访问量 358

猜你喜欢

转载自blog.csdn.net/weixin_44074551/article/details/104779300