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
不积跬步,无以至千里;不积小流,无以成江海。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· 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工具