【问题标题】:Gradle replace resource file with WAR pluginGradle 用 WAR 插件替换资源文件
【发布时间】:2013-07-25 12:58:04
【问题描述】:

我正在尝试用 Gradle 替换我的 WAR 插件任务中的资源文件。

基本上我有两个资源文件:

database.properties
database.properties.production

我想要实现的是在 WEB-INF/ 下的最终 WAR 文件中将 'database.properties' 替换为 'database.properties.production'

我尝试了很多东西,但对我来说最合乎逻辑的是以下不起作用:

    war {
        webInf {
            from ('src/main/resources') {
                exclude 'database.properties'
                rename('database.properties.production', 'database.properties')
                into 'classes'
            }
        }
    }

但这会导致所有其他资源文件重复,包括重复的 database.properties(两个同名的不同文件)并且 database.properties.production 仍然在 WAR 中。

我需要一个干净的解决方案,在 WAR 中没有重复且没有 database.properties.production。

【问题讨论】:

    标签: resources gradle war


    【解决方案1】:

    如果您无法在运行时做出决定(这是处理特定环境配置的推荐最佳做法),eachFile 可能是您的最佳选择:

    war {
        rootSpec.eachFile { details -> 
            if (details.name == "database.properties") {
                details.exclude()
            } else if (details.name == "database.properties.production") {
                details.name = "database.properties"
            }
        }
    }
    

    PS:Gradle 1.7 增加了filesMatching(pattern) { ... },其性能可能比eachFile 更好。

    【讨论】:

    • 刚试了,还是不行。好像没什么效果。 :S
    • 我已经更新了代码并验证了它是否有效。简而言之,更改不符合您需求的现有配置(在本例中是由 war 插件完成的配置)可能会很棘手。有时最好以不同的方式解决问题。在这种情况下,一种替代方法是删除processResources.doLast { ... } 中的“错误”文件(并重命名另一个文件)。或者,您可以将文件放在src/main/resources 以外的位置,并根据需要手动包含它们 (war.webInf.from ...)。哪种解决方案最好取决于您的确切需求(IDE 集成等)。
    • 成功了。谢谢。我选择这种方法的原因是它需要最少的工作。我不想将属性保存在单独的位置。使用这种方法,当我使用我的 IDE 时,我的代码会在 database.properties 中看到测试数据库,当我生成我的 WAR 时,我知道我正在设置生产数据库。
    【解决方案2】:

    如果您想要一个适用于多个归档任务的解决方案,那么您可以在 processResources 任务执行后修改“build/resources/main”中的属性文件。我不确定这是否是一种公认​​的做法。我使用从 build 文件夹生成的两个归档任务 jar 和 par,所以这对我有用。

    此外,以下解决方案使用以“.production”结尾的所有文件。

    我用 Gradle 1.11 测试了这个解决方案

    classes << {
        FileTree tree = fileTree(dir: "build/resources/main").include("*.production")
        tree.each { File file ->
            String origName = file.name.substring(0, file.name.length() - ".production".length())
            File orig = new File(file.getParent(), origName)
            orig.delete()
            file.renameTo(orig)
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      • 2010-09-24
      • 2014-03-13
      • 1970-01-01
      相关资源
      最近更新 更多