![从Gradle构建脚本中提取常用方法 从Gradle构建脚本中提取常用方法](https://c1.lmlphp.com/image/static/default_avatar.gif)
本文介绍了从Gradle构建脚本中提取常用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个Gradle构建脚本( build.gradle
),其中我创建了一些任务。这些任务主要由方法调用组成。被调用的方法也在构建脚本中。
现在,情况如下:
我创建了大量的构建脚本,其中包含不同的任务,但是使用原始脚本中的相同方法。因此,我想以某种方式提取这些常用方法,因此我可以轻松地重复使用它们,而不是将其复制到我创建的每个新脚本中。
如果Gradle是PHP,类似以下内容将是理想的:
//脚本内容
...
require(common-methods.gradle);
...
//更多脚本内容
但当然,是不可能的。或者是它?
无论如何,我怎么能达到这个结果?什么是最好的方法来做到这一点?我已经通读了Gradle文档,但似乎无法确定哪种方法最简单,最适合这种方法。
预先感谢! / p>
更新:
我已经设法在另一个文件中提取方法
(使用 apply from:'common-methods.gradle'
),
所以结构如下:
父/
/build.gradle //原始构建脚本
/common-methods.gradle //提取的方法
/gradle.properties //构建脚本使用的属性
从 build.gradle
执行任务后,我碰到了成为一个新问题:显然,当它们在 common-methods.gradle
中时,方法不会被识别。
共享方法是不可能的,但你可以共享包含闭包的额外属性,归结为相同的东西。例如,在 common-methods.gradle
中声明 ext.foo = {...}
,使用 apply from:
来应用脚本,然后用 foo()
调用闭包。
I have a Gradle build script (build.gradle
), in which I created some tasks. These tasks consist mostly of method calls. The called methods are also in the build script.
Now, here's the situation:
I am creating a fair amount of build scripts, which contain different tasks, but utilise the same methods from the original script. Thus, I would like to extract these "common methods" in some way, so I can easily re-use them instead of copying them for each new script I create.
If Gradle were PHP, something like the following would be ideal:
//script content
...
require("common-methods.gradle");
...
//more script content
But of course, that isn't possible. Or is it?
Anyway, how can I achieve this result? What is the best possible method to do this? I've read through the Gradle documentation already, but I can't seem to determine which method will be the easiest and best suited for this.
Thanks in advance!
UPDATE:
I've managed to extract the methods in another file
(using apply from: 'common-methods.gradle'
),
so the structure is as follows:
parent/
/build.gradle // The original build script
/common-methods.gradle // The extracted methods
/gradle.properties // Properties used by the build script
After executing a task from build.gradle
, I've bumped into a new problem: apparently, methods don't get recognized when they're in common-methods.gradle
.
Any ideas on how to fix that?
解决方案
It isn't possible to share methods, but you can share extra properties containing a closure, which boils down to the same thing. For example, declare ext.foo = { ... }
in common-methods.gradle
, use apply from:
to apply the script, and then call the closure with foo()
.
这篇关于从Gradle构建脚本中提取常用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!