gradle 替换项目里用的properties变量名 [gradle访问带点号的key/value]

背景:最近使用Vault来管理用户名和密码时,需要在项目配置文件vault.properties文件里使用占位符来写入变量名,gradle编译期间填入相关环境的roleId & secretId.

 

vault.properties

vault.roleId=${vault.roleId}

vault.secretId=${vault.secretId}

 

build.gradle 文件里定义替换变量的task

// replace vault roleId & secretId
processResources {
    if (project.hasProperty("vault.roleId") && project.hasProperty("vault.secretId")){
        filesMatching("**/vault.properties") {
            println("replace vault key for ["+it.relativePath+"] ...")
            expand project.properties
        }
    }
} 

抛出异常:

Execution failed for task ':vault-java:processResources'.
> Could not copy file '/Users/adorechen/IdeaProjects/vault-java/src/main/resources/vault.properties' to '/Users/adorechen/IdeaProjects/vault-java/build/resources/main/vault.properties'.
 

add argument: "--stacktrace"

Caused by: groovy.lang.MissingPropertyException: No such property: vault for class: SimpleTemplateScript2
        at SimpleTemplateScript2.run(SimpleTemplateScript2.groovy:3)
        at org.gradle.api.internal.file.copy.FilterChain$3.transform(FilterChain.java:121)
        at org.gradle.api.internal.file.copy.FilterChain$3.transform(FilterChain.java:110)
        at org.gradle.api.internal.ChainingTransformer.transform(ChainingTransformer.java:37)
        at org.gradle.api.internal.file.copy.FilterChain.transform(FilterChain.java:56)
        at org.gradle.api.internal.file.copy.FilterChain.transform(FilterChain.java:64)
        at org.gradle.api.internal.file.copy.DefaultFileCopyDetails.open(DefaultFileCopyDetails.java:88)
        at org.gradle.api.internal.file.AbstractFileTreeElement.copyTo(AbstractFileTreeElement.java:56)
        at org.gradle.api.internal.file.copy.DefaultFileCopyDetails.copyTo(DefaultFileCopyDetails.java:96)
        at org.gradle.api.internal.file.AbstractFileTreeElement.copyFile(AbstractFileTreeElement.java:93)
 

原因在于groovy默认${vault.roleId}时把vault作为变量名,查找时不能找到vault相关变量,然后抛出异常。

解决方案:使用getProperty("vault.roleId")来访问变量即可。

 

vault.roleId=${getProperty("vault.roleId")}
vault.secretId=${getProperty("vault.secretId")}

 

OK,重新打包编译,通过。

 

参考:

gradle properties 优先级及访问 https://mp.csdn.net/postedit/89437115 

你可能感兴趣的:(gradle)