1. 程式人生 > >maven 打包時動態替換properties資源文件中的配置值

maven 打包時動態替換properties資源文件中的配置值

mave tools false sof get per 執行 ces pre

pom build節點下面添加resource配置:

[html] view plain copy
  1. <resources>
  2. <resource>
  3. <directory>src/main/resources/</directory>
  4. <filtering>true</filtering>
  5. <includes>
  6. <include>**/*.properties</include>
  7. </includes>
  8. </resource>
  9. <resource>
  10. <directory>src/main/resources/</directory>
  11. <filtering>false</filtering>
  12. <includes>
  13. <include>**/*.xml</include>
  14. </includes>
  15. </resource>
  16. </resources>
[html] view plain copy

resource的filtering屬性用來表示資源文件中的占位符是否需要被替換,true為需要替換。

上面的定義是所有的.properties文件中的EL表達式占位符都會在打包時動態替換,所有的.xml文件則不會替換占位符。

接下來我們配置兩個profile,一個是測試環境,一個是正式環境配置:

[html]
view plain copy
  1. <profiles>
  2. <profile>
  3. <id>dev</id>
  4. <properties>
  5. <jest.urls>http://n2:9200,http://n4:9200</jest.urls>
  6. </properties>
  7. <activation>
  8. <activeByDefault>true</activeByDefault>
  9. </activation>
  10. </profile>
  11. <profile>
  12. <id>production</id>
  13. <properties>
  14. <jest.urls>http://192.168.3.241:9200,http://192.168.3.242:9200</jest.urls>
  15. </properties>
  16. </profile>
  17. </profiles>


我們再在src/main/resources目錄下面創建一個config.properties文件,內容如下:

jest.urls=${jest.urls}

然後我們執行maven打包命令:clean package -DskipTests -Pdev

查看對應的jar包裏面的config.properties文件,可以發現占位符已經被替換成了profile dev中配置的jest.urls的值。

maven 打包時動態替換properties資源文件中的配置值