我正在将构建从Maven转换为Gradle,并在其中进行一些资源过滤。具体来说,我们有一个如下所示的块:
<build>
<finalName>${project.name}-${project.version}</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/test/resources</directory>
<filtering>true</filtering>
</testResource>
</testResources>
<filters>
<filter>/path/to/more/resources.properties</filter>
<filter>/path/to/more/resources.properties</filter>
<filter>/path/to/more/resources.properties</filter>
</filters>
</build>
...而我们希望在Gradle中获得类似的东西。
the Copy tasks with filter in them的文档还不完整,没有描述我要解决的具体问题:
${example.property}
)我将如何去做呢?
最佳答案
这是this Gradle-oriented answer的扩展,提供了一些更具体的示例。
首先,我们需要将所有我们关心的资源读入“复制”任务的filter
方法将识别的内容。按照惯例,这只是一个标准的Properties
对象。
可以这样完成:
def resources = new Properties()
file($projectDir/src/main/resources/<insert-properties-file>.properties").withInputStream {
resources.load(it)
}
请注意,可能有一种更优雅的方式可以一次获取多个属性文件。这种方法对我来说仅适用于一个文件。
接下来,我们需要实际进行过滤。这可以通过
from
闭包来完成。我们利用ReplaceTokens class(我们可以导入)进行此操作,并配置begin和end token 以匹配我们的变量用法。from("$projectDir/path/to/folder/that/has/tokens/to/replace") {
include "**/files-to-filter-on"
filter(ReplaceTokens, tokens: resources, beginToken: "${", endToken: "}")
}
为了使它进入WAR,我们需要将其加载到
processResources
任务中。全部一起:
processResources {
with copySpec {
def resources = new Properties()
file($projectDir/src/main/resources/<insert-properties-file>.properties").withInputStream {
resources.load(it)
}
from("$projectDir/path/to/folder/that/has/tokens/to/replace") {
include "**/files-to-filter-on"
filter(ReplaceTokens, tokens: resources, beginToken: "${", endToken: "}")
}
}
当执行
./gradlew clean war
时,您要过滤的资源将在归档中正确过滤。
关于maven - 我正在将Maven WAR构建迁移到Gradle。我如何使过滤器 block 以相同的方式运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218290/