使用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中的变量配置替换成固定值

原文地址:https://www.cnblogs.com/zhjh256/p/6880715.html