如何在多项目gradle构建系统中使用变量?

时间:2016-06-23 10:54:21

标签: java gradle build multi-project

我有一个用gradle管理的多项目结构。所有java子项目都有jar块:

def main_class = "foo.Main"
jar {
    manifest {
        attributes 'Main-Class': main_class
    }
}

所以我决定将jar块移动到根项目中,并且在子项目中只有def main_class,但不管我如何定义main_class变量,它没用。我也尝试了project.extproperties {}

我有一个名为dist的任务,与project.ext合作:

根项目:

subprojects {
    task dist(dependsOn: jar) << {
        copy {
            from('build/libs') {
                include (build_jar)
            }
            into('.')
            rename(build_jar, app_jar)
        }
    }
}

子项目:

project.ext {
    build_jar = "..."
    app_jar = "..."
}

如何定义与jar一起使用dist任务的变量?

2 个答案:

答案 0 :(得分:0)

你可以这样做:

ext {
  main_class = 'com.Main'
}

subprojects {
  apply plugin: 'java'
  jar {
    manifest {
        attributes 'Main-Class': main_class
    }
  }
}

PROJECT_ROOT/build.gradle档案中。

答案 1 :(得分:0)

要覆盖子项目的build.gradle中的其他属性,必须将所需的任务(在本例中为jar task)放在afterEvaluate块中。

根项目build.gradle:

subprojects {
    apply plugin: 'java'
    apply plugin: 'application'

    ext {
        // the property that should be overridden in suproject's build.gradle
        main_class = ''
    }

    afterEvaluate {
        jar {
            manifest {
                attributes 'Main-Class': main_class
            }
        }
    }
}

子项目build.gradle:

mainClassName = 'project.specific.Main'
ext.set("main_class", mainClassName)
// you could also use this notation, but I prefer the first one
// since it is more clear on what it is doing
//main_class = mainClassName