zhaoyu@home:~$

gradle-依赖管理

依赖配置

  • compile 编译范围依赖在所有的 classpath 中可用,同时它们也会被打包
  • runtime runtime 依赖在运行和测试系统的时候需要,但在编译的时候不需要。比如,你可能在编译的时候只需要 JDBC API JAR,而只有在运行的时候 才需要 JDBC 驱动实现
  • testCompile 测试期编译需要的附加依赖
  • testRuntime 测试运行期需要

外部依赖

dependencies {
    compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.7.Final'
}

外部依赖包含 group,name 和 version 几个属性。也可以使用简洁方式将三个属性拼接在一起即可。”group:name:version”

dependencies {
    compile 'org.hibernate:hibernate-core:3.6.7.Final'
}

java项目的一个典型依赖如下:

//引入java插件,我们就可以使用 'implementation', 'testImplementation' 配置了
apply plugin: 'java'

dependencies {
  //使用 group:name:version 样式
  implementation 'commons-lang:commons-lang:2.6'
  testImplementation 'org.mockito:mockito:1.9.0-rc1'

  //map风格样式:
  implementation group: 'com.google.code.guice', name: 'guice', version: '1.0'

  //任意的文件作为依赖
  implementation files('hibernate.jar', 'libs/spring.jar')

  //将所有'libs' 中的jar放入 编译路径。
  implementation fileTree('libs')
}

高级配置中,可以操作排除那些配置等:

apply plugin: 'java' 

dependencies {
  implementation('org.hibernate:hibernate:3.1') {
    //如果存在版本冲突,强制使用3.1
    force = true

    //排除指定的传递依赖
    exclude module: 'cglib' //by artifact name
    exclude group: 'org.jmock' //by group
    exclude group: 'org.unwanted', module: 'iAmBuggy' //by both name and group

    //禁止该依赖所有的传递依赖
    transitive = false
  }
}

buildscript

buildscript 中的声明是gradle脚本自身需要使用的资源。通常包括插件等。而build.gradle中直接声明的依赖项、仓库地址等信息是项目自身需要的资源。 gradle在执行脚本时,会优先执行buildscript代码块中的内容,然后才会执行剩余的build脚本。

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
        classpath "io.spring.gradle:dependency-management-plugin:$springDependencyManagementPluginVersion"
    }

}