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新手村系列】(14)人机交互
java·spring boot·spring
唐青枫6 天前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
咖啡八杯8 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
Flittly9 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
dunky9 天前
Spring 的三级缓存与循环依赖
后端·spring
码云数智-园园14 天前
C++20 Modules 模块详解
java·开发语言·spring
咖啡八杯14 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
Flittly14 天前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
李少兄14 天前
从原理到实战:Spring IoC/DI 核心知识体系与高频面试题全解
java·后端·spring