我的 spring-boot 应用程序有一个 build.gradle 文件。对于一些 gradle 任务,我希望更改一些环境细节。专门针对 gradle 任务“test”、“runSmokeTest”和“bootRun”。在所有任务中,我都必须进行相同的调用,所以我希望能从中提取出一个方法。或者一个任务。但是每当我这样做时,突然 gradle 不再找到我需要的功能。
这些是我需要调用的电话:
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
当直接包含在
bootRun
中时,该代码工作得非常好。任务,test
任务和runSmokeTest
通过复制'n'粘贴任务。我不想重复代码。我尝试了以下方法从 bootRun 任务中提取它们,但 Gradle 一直提示他找不到函数 systemProperty
和 environment
.同样,如果我使用 Intellij 集成功能“提取方法”:task specialConfiguration() {
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
}
bootRun {
dependsOn 'specialConfiguration'
}
如何从 3 个任务中提取这段短代码以避免重复代码?
最佳答案
Gradle keeps complaining that he does not find the functions
systemProperty
andenvironment
这是一个典型的例子,其中 Kotlin DSL会发光。您将确切地知道在任何给定时间可用的方法/属性,因为它是一种与 Groovy 不同的强类型语言。
话虽如此,当您执行以下操作时:
task specialConfiguration() {
systemProperties System.properties
systemProperty "spring.cloud.config.failFast", "false"
if (project.hasProperty("TEAM_ENCRYPT_KEY"))
environment "ENCRYPT_KEY", "$TEAM_ENCRYPT_KEY"
}
bootRun {
dependsOn 'specialConfiguration'
}
你是:
specialConfiguration
的任务. bootRun
依赖的任务specialConfiguration
我想你假设
dependsOn
就像“配置”一个任务,实际上它只是向任务添加依赖项。见 Adding dependencies to a task .我假设
runSmokeTest
是 Test
类型.所以任务test
, runSmokeTest
, 和 bootRun
全部执行JavaForkOptions systemProperties(..)
所在的界面, systemProperty(.., ..)
和 environment(.., ..)
方法来自。话虽如此,既然您知道要配置的三个任务,并且它们都实现了
JavaForkOptions
并且以某种方式,您可以这样做(Kotlin DSL):import org.springframework.boot.gradle.tasks.run.BootRun
// Assuming this is a Test task type
tasks.register("runSmokeTest", Test::class)
// Define a new Action (configuration)
val taskConfig = Action<JavaForkOptions> {
systemProperties(System.getProperties() as Map<String, Any>)
systemProperty("spring.cloud.config.failFast", false)
if (project.hasProperty("TEAM_ENCRYPT_KEY")) {
environment("ENCRYPT_KEY", project.property("TEAM_ENCRYPT_KEY")!!)
}
}
// Configure all three tasks
tasks.named("test", Test::class, taskConfig)
tasks.named("runSmokeTest", Test::class, taskConfig)
tasks.named("bootRun", BootRun::class, taskConfig)
关于spring-boot - 如何避免在gradle中复制'n'paste?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61001173/