Gradle实现类似Maven的profiles功能

版本说明

  1. GraalVM JDK 21.0.3
  2. Gradle 8.7
  3. Spring Boot 3.2.5

目录结构

指定环境打包

application.yml/yaml/properties

执行 bootJar 打包命令前要先执行 clean【其它和 processResources 相关的命令也要先执行 clean】,否则 active 值不会变!

yaml 复制代码
spring:
  profiles:
    # 执行 bootJar 打包命令前要先执行 clean【其它和 processResources 相关的命令也要先执行 clean】,否则 active 值不会变!
    active: @activeProfiles@

build.gradle 修改 processResources 任务

yaml 复制代码
def activeProfiles = project.properties['activeProfiles'] ?: "dev"
processResources {
    exclude {
        FileTreeElement details ->
            {
                (//排除不是当前环境的 yml 配置文件
                        details.file.name.startsWith("application-")
                                && details.file.name.endsWith(".yml")
                                && !details.file.name.equals("application.yml")
                                && !details.file.name.equals("application-" + activeProfiles + ".yml")
                ) || (//排除不是当前环境的 yaml 配置文件
                        details.file.name.startsWith("application-")
                                && details.file.name.endsWith(".yaml")
                                && !details.file.name.equals("application.yaml")
                                && !details.file.name.equals("application-" + activeProfiles + ".yaml")
                ) || (//排除不是当前环境的 properties 配置文件
                        details.file.name.startsWith("application-")
                                && details.file.name.endsWith(".properties")
                                && !details.file.name.equals("application.properties")
                                && !details.file.name.equals("application-" + activeProfiles + ".properties")
                )
            }
    }
    filter ReplaceTokens, tokens: [
            activeProfiles: activeProfiles
    ]
}

打包

因为没有指定环境,默认dev

可以先在build/resources/main目录下查看是否只包含对应环境的文件


jar包里的文件和变量也对的上

指定test环境打包

bootJar追加application.yml配置的spring.profiles.active的@activeProfiles@变量名并指定环境为test后点ok保存

先clean再bootJar,否则不会生效!!!

打包输出到控制台的命令可以查看配置有没有生效

查看文件是否符合预期

相关推荐
Wang15301 小时前
jdk内存配置优化
java·计算机网络
0和1的舞者2 小时前
Spring AOP详解(一)
java·开发语言·前端·spring·aop·面向切面
Wang15302 小时前
Java多线程死锁排查
java·计算机网络
小小星球之旅2 小时前
CompletableFuture学习
java·开发语言·学习
利刃大大3 小时前
【SpringBoot】Spring事务 && @Transactional详解 && Spring事务失效问题
spring boot·spring·事务
jiayong233 小时前
知识库概念与核心价值01
java·人工智能·spring·知识库
皮皮林5513 小时前
告别 OOM:EasyExcel 百万数据导出最佳实践(附开箱即用增强工具类)
java
Da Da 泓4 小时前
多线程(七)【线程池】
java·开发语言·线程池·多线程
To Be Clean Coder4 小时前
【Spring源码】getBean源码实战(三)
java·mysql·spring
Wokoo74 小时前
开发者AI大模型学习与接入指南
java·人工智能·学习·架构