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

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

查看文件是否符合预期

相关推荐
万年咸鱼6 分钟前
Java BufferedInputStream 详解:原理、用法与实战
java·开发语言·python
~木雨27 分钟前
Java 线程池七问七答:参数、执行流程、拒绝策略到 ThreadLocal 内存泄漏,面试必背
java·面试·线程池·threadlocal·threadpool·executor
艾莉丝努力练剑44 分钟前
【AI大模型接入SDK】Gemini模型接入知识体系
java·开发语言·网络·人工智能·网络协议·学习·http
云运维笔记1 小时前
Zabbix 分布式监控搭建实战:基于 Proxy 实现 MySQL、Java、Nginx 监控
java·mysql·zabbix
zhanghaha13141 小时前
Python进阶教程:28_queue 队列模块 零基础超详细教程
java·开发语言·python
司小豆1 小时前
第七课:DeepSeek Harness 服务与依赖注入
java·服务器·开发语言·github·ai编程
许彰午1 小时前
24-MyBatisHelper与autoCount
java·低代码·架构
CRMEB系统商城1 小时前
汽车养护连锁的数字化底座CRMEB 多门店系统实战方案
java·开发语言·小程序·开源·汽车
学编程就要猛2 小时前
使用Spring AI配置聊天大模型实现人机交互(初阶)
java·spring ai·advisor·chatclient·chatmodel
Dreams_l2 小时前
RabbitMQ在SpringBoot中的应用
spring boot·rabbitmq·java-rabbitmq