gradle通过def定义变量指定依赖版本

在实际应用中,我们的项目会需要很多依赖,很多时候一些相关依赖的版本需要统一。我们拿springboot来举例,加上我们的项目是web项目,ORM采用JPA,那么我们就需要spring-boot-starter-web和spring-boot-starter-data-jpa,这时候依赖如下:

dependencies {
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.0.2.RELEASE'

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '2.0.2.RELEASE'

    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.8-dmr'
}

这时候两个起步依赖用的版本都是2.0.2.RELEASE,假设我现在想用2.0.3.RELEASE的起步依赖,那么我就需要找到依赖中所有起步依赖,然后一个个去修改为2.0.3.RELEASE,如果依赖非常多的话,这样去做明显是不划算的,我们可以通过def定义一个变量来指定版本,在具体依赖中调用它即可,如下:

def springBootVersion = '2.0.3.RELEASE'
def mysqlConnectorVersion = '8.0.8-dmr'

dependencies {
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: "$springBootVersion"

    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: "$springBootVersion"

    // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    compile group: 'mysql', name: 'mysql-connector-java', version: "$mysqlConnectorVersion"
}

通过def定义版本变量,然后在依赖调用即可,这样便于版本的统一管理,也便于查看。def定义的字符串变量,通过$符号即可引用,需要注意的是,需要用def定义的变量时,字符串需要用双引号“” 而不能用单引号‘’

猜你喜欢

转载自blog.csdn.net/qq_36666651/article/details/80718761