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

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

查看文件是否符合预期

相关推荐
xdl25995 分钟前
Spring Boot中集成MyBatis操作数据库详细教程
数据库·spring boot·mybatis
回到原点的码农5 分钟前
Spring Data JDBC 详解
java·数据库·spring
gf13211118 分钟前
python_查询并删除飞书多维表格中的记录
java·python·飞书
zb2006412010 分钟前
Spring Boot 实战:轻松实现文件上传与下载功能
java·数据库·spring boot
一勺菠萝丶27 分钟前
Flowable + Spring 集成踩坑:流程结束监听器查询历史任务为空 & 获取不到审批意见
java·数据库·spring
jwn99932 分钟前
Spring Boot 整合 Keycloak
java·spring boot·后端
宁波阿成32 分钟前
OpenClaw 在 Ubuntu 22.04.5 LTS 上的安装与问题处理记录
java·linux·ubuntu·openclaw·龙虾
mldlds33 分钟前
SpringBoot详解
java·spring boot·后端
kang_jin33 分钟前
Spring Boot 自动配置
java·spring boot·后端
sg_knight40 分钟前
如何用 Claude Code 做大型项目重构与架构优化
java·重构·架构·llm·claude·code·claude-code