Maven打包項目是能夠經過-P 參數, 使用profile, 向build配置中傳遞相關的環境配置信息, 例如html
Spring Boot默認提供了很好的多環境配置打包的方案.
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-loading-yamlspring
和經過配置文件的環境命名獲取相應環境的配置數據庫
以下定義env的三種參數, 設置dev爲默認激活(爲開發調試方便)maven
<profiles> <profile> <id>dev</id> <properties> <env>dev</env> </properties> <activation> <activeByDefault>true</activeByDefault> </activation> </profile> <profile> <id>test</id> <properties> <env>test</env> </properties> </profile> <profile> <id>prod</id> <properties> <env>prod</env> </properties> </profile> </profiles>
pom.xml中就有了變量 ${env}
ide
${env}
在build中使用該變量去引入不一樣環境的配置文件spring-boot
<build> <finalName>xxxxxx</finalName> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>config-${env}.properties</include> <include>config.properties</include> <include>**.xml</include> </includes> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build>
使用${env}
引入 src/main/resources
中不一樣環境的配置文件測試
全部按照上述的配置後, 在項目spring初始化引入配置文件 須要作以下設置ui
<context:property-placeholder file-encoding="utf-8" ignore-resource-not-found="true" ignore-unresolvable="false" location=" classpath:/config.properties, classpath:/config-dev.properties, classpath:/config-test.properties, classpath:/config-prod.properties" />
ignore-resource-not-found
設置爲true
由於配置了按環境配置文件打包,項目啓動時,只會出現啓動兩個properties, config.properties
和config-{evn}.properties
, 配置的另外兩個文件是查找不到.spa
ignore-unresolvable
設置爲 false
防止出現配置缺失的問題, 及時報錯調試
location
按以下配置路徑,加載的順序爲依次的配置文件依次寫順序.
因此先加載默認的 config.properties
, 該文件能夠寫一些公用,相同的配置參數.config-${env}.propertis
寫一些系統的參數, 好比數據庫鏈接信息.