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

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

查看文件是否符合预期

相关推荐
Kuo-Teng32 分钟前
LeetCode 198: House Robber
java·算法·leetcode·职场和发展·动态规划
q***72561 小时前
Spring Boot + Vue 全栈开发实战指南
vue.js·spring boot·后端
小七mod1 小时前
【Spring】Spring Boot自动配置的案例
java·spring boot·spring·自动配置·源码·ioc·aop
java干货1 小时前
Spring Boot 为什么“抛弃”了 spring.factories?
spring boot·python·spring
红石榴花生油1 小时前
Docker + Nginx 部署 Java 项目(JAR 包 + WAR 包)实战笔记
java·tomcat·maven
清晨细雨~1 小时前
SpringBoot整合EasyExcel实现Excel表头校验
spring boot·后端·excel
带刺的坐椅1 小时前
Solon AI 开发学习 - 1导引
java·ai·openai·solon·mcp
sg_knight1 小时前
RabbitMQ 中的预取值(prefetch)详解:如何真正提升消费端性能?
java·spring boot·spring·spring cloud·消息队列·rabbitmq·预取值
Dxxyyyy1 小时前
零基础学JAVA--Day34(Map接口+HashTable+HashMap+TreeSet+TreeMap+开发中如何选择集合实现类?(重要))
java·开发语言
spencer_tseng2 小时前
Tomcat Source Code Distributions
java·tomcat