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,否则不会生效!!!

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

查看文件是否符合预期

相关推荐
mike04124 小时前
Eclipse+maven+selenium自动化测试用例入门
selenium·eclipse·maven
wniuniu_4 小时前
object->osd
android·java·数据库
猫头虎4 小时前
IntelliJ IDEA 2025.3 最新变化:值得更新吗?
java·开发语言·ide·人工智能·intellij-idea·idea·gitcode
猫豆~4 小时前
ceph分布式存储——1day
java·linux·数据库·sql·云计算
爱吃烤鸡翅的酸菜鱼4 小时前
Spring Boot 注解全栈指南:涵盖 Bean 注册、配置加载、请求映射、事务控制、数据校验等一网打尽
java·开发语言·spring boot·后端·spring
running up4 小时前
Spring IOC与DI核心注解速查表
java·后端·spring
YDS8294 小时前
SpringCloud —— Sentinel详解
java·spring cloud·sentinel
洛阳泰山4 小时前
快速上手 MaxKB4J:开源企业级 Agentic 工作流系统在 Sealos 上的完整部署指南
java·人工智能·后端
guslegend4 小时前
SpringSecurity授权原理与实战
java
原来是好奇心4 小时前
深入Spring Boot源码(七):测试框架原理与最佳实践
java·源码·springboot