当存在特定依赖项时,我需要在gradle中动态添加依赖项。
我用它来检查是否存在特定的依赖关系
def hasSb2 = false
def sb2InModule = false
def sbInModule = false
allprojects {
project ->
afterEvaluate {
if (project.name == "XXX") {
def dependency = project.configurations.getByName("compile").allDependencies.find { c -> c.group == "org.springframework.boot" }
if (null != dependency) {
sbInModule = true
if (dependency.version.startsWith("1")) {
println(dependency.version)
println(project.name)
sb2InModule = true
}
}
}
project.subprojects.each {
sp ->
if (sp.name== "XXX") {
def dependency = sp.configurations.getByName("compile").allDependencies.find { c -> c.group == "org.springframework.boot" }
if (null != dependency && dependency.version.startsWith("1")) {
println(dependency.version)
println(sp.name)
hasSb2 = true
}
}
}
}
}
我使用以下脚本更改依赖项
allprojects {
afterEvaluate {
project ->
if (project.name == "XXX") {
if (sb2InModule || (!sbInModule && hasSb2)) {
println("ready to insert")
println(project.buildscript.configurations.getByName("classpath").allDependencies)
project.buildscript.getDependencies().add("classpath","org.springframework:spring-webmvc:5.2.6.RELEASE")
println(project.buildscript.configurations.getByName("classpath").allDependencies)
}
}
}
}
但是我得到了例外
A problem occurred configuring project ':XXX'.
> Cannot change dependencies of configuration ':XXX:classpath' after it has been resolved.
所以我想知道评估后如何在init.gradle中添加依赖项