使用maven profile指定配置文件打包适用多环境

开发过程, 我们习惯把数据源配置, 项目常量, 日志配置等基础数据配置写到一个个单独的的文件中. 如jdbc.properties等各种.格式的文件.

 

如何不频繁修改配置文件, 随时打包不同基础数据配置信息的项目.

 

文中有大图片, 阅读时模糊, 建议用鼠标左键按住,把图片拖到浏览器新的窗口去看.

1.新建maven项目,   在pom.xml中添加 profile节点信息如下:

 

[html] view plain copy

  1. <profiles>  
  2.         <profile>  
  3.               
  4.             <id>devid>  
  5.             <properties>  
  6.                 <environment>developmentenvironment>  
  7.             properties>  
  8.             <activation>  
  9.                 <activeByDefault>trueactiveByDefault>  
  10.             activation>  
  11.         profile>  
  12.         <profile>  
  13.               
  14.             <id>testid>  
  15.             <properties>  
  16.                 <environment>testenvironment>  
  17.             properties>  
  18.         profile>  
  19.         <profile>  
  20.               
  21.             <id>previd>  
  22.             <properties>  
  23.                 <environment>previewenvironment>  
  24.             properties>  
  25.         profile>  
  26.         <profile>  
  27.               
  28.             <id>prodid>  
  29.             <properties>  
  30.                 <environment>productionenvironment>  
  31.             properties>  
  32.         profile>  
  33. profiles>  

 

 

 

 

 2. 在项目中添加各环境需要的数据源配置文件,分不同目录存放, 分别是开发,测试, 预演,生产  环境. 如下图左边部分所示.  

 

3. pom.xml中配置resource节点信息.

[html] view plain copy

  1. <build>             
  2.     <resources>  
  3.         <resource>  
  4.             <directory>src/main/resourcesdirectory>  
  5.             <excludes>  
  6.                 <exclude>environment/development/*exclude>    
  7.                 <exclude>environment/test/*exclude>    
  8.                 <exclude>environment/preview/*exclude>    
  9.                                 <exclude>environment/production/**exclude>  
  10.             excludes>  
  11.         resource>  
  12.         <resource>  
  13.             <directory>src/main/resources/environment/${environment}directory>  
  14.             <targetPath>environment/${environment}targetPath>  
  15.         resource>  
  16.     resources>  
  17. build>  

 

resource节点信息解释: 

 

[html] view plain copy

  1. <directory>src/main/resourcesdirectory>   
  2. <exclude>environment/development/**exclude>   
  3. <exclude>environment/test/**exclude>   
  4. <exclude>environment/preview/**exclude>   
  5. <exclude>environment/production/**exclude>  
  6.   
  7.   

 

[html] view plain copy

  1. <directory>src/main/resources/environment/${environment}directory>   
  2. <targetPath>environment/${environment}targetPath>  


4.  项目打包.   打包命令mvn package -Pdev来指定激活id为 dev 的profile节点, 这样, 开发环境配置文件就会被打包.
开发: mvn package -Pdev (因为配置了默认激活dev部分, 所以也可以使用mvn package, 这与 mvn package -Pdev 效果相同)
测试: mvn package -Ptest
预演:mvn package -Pprev
生产:mvn package -Pprod

你可能感兴趣的:(笔记)