在实际开发过程中,可能需要不断进行环境的切换和打包部署,通常我们会选择在application.properties中修改不同环境对应的配置文件,这种方式不仅效率低,而且很容易发生错误,造成不必要的麻烦降低工作效率。

Gradle中并没有直接类似Maven中的profiles支持,但是可以在processResources 任务中写一些脚本,通过传入的系统属性profile值来支持.

例如运行gradle build时,传入profile系统属性

  • 打包开发环境: gradlew build -Dprofile=dev
  • 打包测试环境: gradlew build -Dprofile=test
  • 打包生产环境: gradlew build -Dprofile=prod

build.gradle文件里添加:

//@wjw_note: 根据传进来的profile系统属性来打包.
//def profileName = System.getProperty("profile") ?: "dev"
def profileName = System.getProperty("profile")
if(profileName==null) {
  throw new BuildCancelledException("must pass The environment variable 'profile'\r\n"
                                   +"For example: gradlew clean build -i -x test --no-daemon -Dprofile=dev")
}

processResources {
    include '**/public/**'
    include '**/static/**'
    include '**/templates/**'
    include '**/tpl/**'
    include '**/i18n/**'
    
    include { FileTreeElement details ->
        details.isDirectory()==true || details.file.name.contains("-${profileName}.")  /* 根据传入的profileName系统属性来过滤 */
    }
}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐