使用 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/