maven properties 动态转换

可以将不同profile的属性直接配置在顶级pom.xml中,这样的优点是各个module可以共用配置的属性。

第一步,新建Spring Boot项目,修改pom.xml,添加<profiles/>配置如下:

复制代码
<profiles>
    <profile>
        <id>dev</id>
        <properties>
            <username>zhangsan</username>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <username>lisi</username>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>
复制代码

 

这里定义了dev和prod两个profile,其中默认激活的是dev。每个profile中通过<properties/>设置了属性。

第二步,修改编译设置。这里的<filtering>true</filtering>指定了使用pom.xml中profile下的属性替换src/main/resources/下${xxx}方式的属性引用:

复制代码
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
复制代码

第三步,在一个module中新建src/main/resources/application.properties,内容为:

username=${username}

 

第四步,在编译命令中使用-P参数指定profile如:mvn clean install -DskipTests –Pdev,来完成指定profile环境的编译。

查看module中的target/classes/application.properties文件,发现当-Pdev时,文件中username=zhangsan,当-Pprod时,文件中username=lisi

posted @   亲爱的阿道君  阅读(365)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示