java - 如果检测到不适当的依赖项,Gradle 构建会失败?

标签 java gradle

使用 Gradle,我想确保在大型项目中进行适当的依赖关系管理,以便模块 A 不能依赖于模块 B(即使是间接依赖)。我该如何去做呢?

最佳答案

您可以分析所有依赖关系,如果发现不合适的依赖关系,则抛出异常。下面是针对类路径的特定依赖项执行此操作的代码:

apply plugin: 'java'
repositories {
    mavenCentral()
}

// This is just to have some dependencies on the classpath.

dependencies {
    compile 'org.springframework.boot:spring-boot-starter:1.5.1.RELEASE'
    compile "org.webjars:webjars-locator:+"
}

// run this task to analyze all deps

task checkDeps {
    doLast {
        // this closure simply prints a given dependency and throws an exception if slf4j-api is found
        def failIfBad = { dep ->
            println "CHECKING: $dep.module.id.group:$dep.module.id.name"
            if (dep.module.id.name == 'slf4j-api') {
                throw new GradleException("$dep.module.id.group:$dep.module.id.name on classpath!")
            }
        }
        // this is a closure with recursion that calls the above failCheck on all children and their children
        def checkChildren
        checkChildren = { dep ->
            if (dep.children.size() != 0) {
                dep.children.each { child ->
                    failIfBad(child)
                    checkChildren(child)
                }
            }
        }
        // this is how you get all dependencies in the compile scope, iterate on the first level deps and then their children
        configurations.compile.resolvedConfiguration.firstLevelModuleDependencies.each { firstLevelDep ->
            failIfBad(firstLevelDep);
            checkChildren(firstLevelDep);
        }
    }
}

整个代码可能会被优化,并且需要更复杂的规则,但它应该为您提供入门所需的内容。

关于java - 如果检测到不适当的依赖项,Gradle 构建会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42918014/

相关文章:

javafx - 使用 gradle 在 JavaFX 中需要位置

eclipse - 如何在 Eclipse 中使用 Buildship 刷新项目依赖项?

java 8 findFirst vs 可选 map

java - Jenkins 上的 Selenium webDriver/Maven java 测试无法与 firefox 通信

java - 无法将日期和时间转换为 LocalDateTime [Java]

java - 建立Android应用程式时发生非预期的最高层异常

java - 将参数传递给 TestNG 运行 - Gradle

css - Spring Boot 不加载 css 文件 : Request method 'GET' not supported

java - 如何在iText7中为单个页面设置页面标签?

java - System.loadLibrary() 从静态 block 返回异常