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

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

一、方案:

  1. 在pom.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)

二、自定义占位符

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

<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>

猜你喜欢

转载自blog.csdn.net/code_nn/article/details/143164086