如何以编程方式设置 gradle 依赖项

How can I set gradle dependencies programatically

如何从文件中以编程方式设置 gradle 依赖项,即 我的 build.gradle

里有这个
dependencies {
  compile "org.springframework.boot:spring-boot-starter-logging"
  compile "org.springframework.boot:spring-boot-autoconfigure"
  compile "org.grails:grails-core"
  compile "org.springframework.boot:spring-boot-starter-actuator"
  compile "org.springframework.boot:spring-boot-starter-tomcat"
  compile "org.grails:grails-dependencies"
  ...
}

我想从如下文件中添加更多依赖项

[
  {env: "runtime", lib : "com.h2database:h2"},
  {env: "runtime", lib : "mysql:mysql-connector-java:5.1.29"}
 ]

有人可以帮助我吗,我是 gradle 的初学者,我需要一个任务来完成它,但我不知道该怎么做

Configuration config = project.configurations.getByName('compile') 
Dependency dep = project.dependencies.create('foo:bar:1.0')
config.add(foo)

你可以这样做:

dependencies {

    def configFile = file('db.config.json');
    def json = new groovy.json.JsonSlurper().parseText(configFile.text)
    json.each {
      "$it.env"(it.lib)
    }

    compile "org.springframework.boot:spring-boot-starter-logging"
    compile "org.springframework.boot:spring-boot-autoconfigure"

    ...
}