Spring 配置文件动态读取pom.xml中的属性

需求:

配置文件中的 spring.profiles.active=${env}需要打包时动态绑定。

一、方案:

  1. 在pom.xml文件中配置启用占位符替换
xml 复制代码
 <profiles>
        <!-- 本地开发 -->
        <profile>
            <id>dev</id>
            <properties>
                <env>dev</env>
            </properties>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <!-- 其他环境 -->
 </profiles>
 <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
</build>

Maven 中 <filtering> 的默认值是 false。这意味着在复制资源文件时,Maven 不会对文件进行占位符替换(即过滤)。

  1. 在配置文件中配置 spring.profiles.active=@env@或者 spring.profiles.active=${env}
  2. 打包时选择环境 mvn clean package -Pprod
    • -P 参数用于激活 Maven 构建中的特定配置文件(profile)

二、自定义占位符

如果担心冲突,那么可以自定义占位符。

xml 复制代码
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <delimiters>
                    <delimiter>#{</delimiter>
                    <delimiter>}</delimiter>
                </delimiters>
                <useDefaultDelimiters>false</useDefaultDelimiters>
            </configuration>
   		</plugin>
    </plugins>
</build>
相关推荐
咖啡八杯19 小时前
GoF设计模式——策略模式
java·后端·spring·设计模式
Flittly2 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
dunky2 天前
Spring 的三级缓存与循环依赖
后端·spring
码云数智-园园7 天前
C++20 Modules 模块详解
java·开发语言·spring
咖啡八杯7 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
Flittly7 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
李少兄7 天前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring
shushangyun_7 天前
2026年快消品B2B系统推荐:支持终端门店订货、促销政策自动化的工具?
java·运维·网络·数据库·人工智能·spring·自动化
ofoxcoding7 天前
在AI API聚合平台配置DeepSeek V3.2提示词缓存实战:快速接入与成本优化指南
人工智能·spring·缓存·ai
一杯奶茶¥7 天前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目