使用maven profile实现多环境配置相关打包

项目开发需要有多个环境,一般为开发,测试,预发,正式4个环境,通过maven可以实现按不同环境进行打包部署,命令为: 

mvn package -P dev

在eclipse中可以右击选项run configuration,输入上述命令。

PS:eclipse maven install和maven packege的区别在于前者除了打包到target外,还会install到本地仓库,这样其他引用的工程就可直接使用。

其中“dev“为环境的变量id, 可以自己定义, 我定义的名称为:dev,qa,pre,prod , 具体在pom.xml中的配置如下:

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  4.     ......  
  5.   
  6.     <profiles>  
  7.         <profile>  
  8.             <id>dev</id>  
  9.             <properties>  
  10.                 <env>dev</env>  
  11.             </properties>  
  12.             <activation>  
  13.                 <activeByDefault>true</activeByDefault>  
  14.             </activation>  
  15.         </profile>  
  16.         <profile>  
  17.             <id>qa</id>  
  18.             <properties>  
  19.                 <env>qa</env>  
  20.             </properties>  
  21.         </profile>  
  22.         <profile>  
  23.             <id>pre</id>  
  24.             <properties>  
  25.                 <env>pre</env>  
  26.             </properties>  
  27.         </profile>  
  28.         <profile>  
  29.             <id>prod</id>  
  30.             <properties>  
  31.                 <env>prod</env>  
  32.             </properties>  
  33.         </profile>  
  34.     </profiles>  
  35.       
  36. ......   
  37.   
  38.     <build>  
  39.         <filters>  
  40.             <filter>config/${env}.properties</filter>  
  41.         </filters>  
  42.         <resources>  
  43.             <resource>  
  44.                 <directory>src/main/resources</directory>  
  45.                 <filtering>true</filtering>  
  46.             </resource>  
  47.         </resources>  
  48.   
  49.         ......  
  50.   
  51.     </build>  
  52. </project>  

 

1.profiles定义了各个环境的变量id

2.filters中定义了变量配置文件的地址,其中地址中的环境变量就是上面profile中定义的值

3.resources中是定义哪些目录下的文件会被配置文件中定义的变量替换,一般我们会把项目的配置文件放在src/main/resources下,像db,bean等,里面用到的变量在打包时就会根据filter中的变量配置替换成固定值

posted @   zhjh256  阅读(329)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
历史上的今天:
2016-05-19 分布式系统基础设施概览
2016-05-19 分布式环境下rabbitmq发布与订阅端
点击右上角即可分享
微信分享提示