maven - 我正在将Maven WAR构建迁移到Gradle。我如何使过滤器 block 以相同的方式运行?

标签 maven gradle war

我正在将构建从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的文档还不完整,没有描述我要解决的具体问题:
  • 过滤掉特定的资源文件
  • 保持变量的POM样式正在使用(${example.property})
  • 确保 Artifact 进入我的WAR

  • 我将如何去做呢?

    最佳答案

    这是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/

    相关文章:

    java - 添加一个附加文件作为项目 Artifact

    intellij-idea - IntelliJ中的Gradle更新破坏了外部库DSL

    android - 将 Firebase 依赖项添加到 Android 项目的 buildSrc 会中断构建

    tomcat - 如何只使用Tomcat的共享lib文件夹?

    perl - 为什么我会收到错误 - "Cannot determine file type for '/tmp/test.war'”?

    java - IntelliJ 和 Maven - 无法创建 Maven 项目

    java - 如何使用 Spring Boot 构建两个重新打包的 jar

    android - 找不到 Gradle DSL 方法'compile()

    java - 如何同时启动部署在tomcat中的所有应用

    java - Spring Boot Maven 单元测试未执行