寫上一篇看英文資料,耗費了心力呀,這章,相對來講簡單點。也比較熟悉,可是這很實用。不扯了,開始~java
在開發應用時,經常使用部署的應用是多個的,好比:開發、測試、聯調、生產等不一樣的應用環境,這些應用環境都對應不一樣的配置項,好比
swagger
通常上在生產時是關閉的;不一樣環境數據庫地址、端口號等都是不盡相同的,要是沒有多環境的自由切換,部署起來是很繁瑣也容易出錯的。git
在沒有使用過
springboot
的多環境配置時,原先是利用maven
的profile
功能進行多環境配置,這裏我簡單回顧下。github
maven配置spring
<profiles> <profile> <id>dev</id> <activation> <activeByDefault>true</activeByDefault> </activation> <properties> <pom.port>8080</pom.port> </properties> </profile> <profile> <id>test</id> <properties> <pom.port>8888</pom.port> </properties> </profile> </profiles> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*</include> </includes> </resource> <resource> <directory>${project.basedir}/src/main/resources</directory> <includes> <include>**/*.properties</include> </includes> <!-- 加入此屬性,纔會進行過濾 --> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <artifactId>maven-resources-plugin</artifactId> <configuration> <encoding>utf-8</encoding> <!-- 須要加入,由於maven默認的是${},而springbooot 默認會把此替換成@{} --> <useDefaultDelimiters>true</useDefaultDelimiters> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
而後編譯時,加入-Ptest
,則會替換test
環境下的參數值。 完整參數:數據庫
mvn clean install -DskipTests -Ptest
application.properties數組
server.port=${pom.port}
利用maven實現多環境配置,比較麻煩的就是每次部署新環境時,都須要再次指定環境編譯打包一次。一下進入主題,springboot
的多環境,比較優雅了許多。springboot
Profile是Spring針對不一樣環境不一樣配置的支持。須要知足application-{profile}.properties
,{profile}
對應你的環境標識。如:微信
application-dev.properties
:開發環境application-test.properties
:測試環境而指定執行哪份配置文件,只須要在application.properties
配置spring.profiles.active
爲對應${profile}
的值。app
# 指定環境爲dev spring.profiles.active=dev
則會加載:application-dev.properties
的配置內容。maven
2018-07-15 14:52:41.304 INFO 15496 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2018-07-15 14:52:41.310 INFO 15496 --- [ main] c.l.l.s.chapter5.Chapter5Application : Started Chapter5Application in 8.506 seconds (JVM running for 10.81) 2018-07-15 14:52:41.316 INFO 15496 --- [ main] c.l.l.s.chapter5.Chapter5Application : 多環境應用啓動.
還能夠在**命令行方式
**激活不一樣環境配置,如
java -jar xxx.jar --spring.profiles.active=test
此時就會加載application-test.properties
的配置內容。 test: dev:
這裏順便提一句,可能在不一樣環境下,可能加載不一樣的bean時,可利用@Profile
註解來動態激活
@Profile("dev")//支持數組:@Profile({"dev","test"}) @Configuration @Slf4j public class ProfileBean { @PostConstruct public void init() { log.info("dev環境下激活"); } }
啓動時。控制檯輸出:
2018-07-15 15:04:44.540 INFO 11876 --- [ main] c.l.l.springboot.chapter5.ProfileBean : dev環境下激活
目前互聯網上不少大佬都有
SpringBoot
系列教程,若有雷同,請多多包涵了。本文是做者在電腦前一字一句敲的,每一步都是親身實踐過的。若文中有所錯誤之處,還望提出,謝謝。
499452441
lqdevOps
完整實例地址:chapter-5
本文地址:https://blog.lqdev.cn/2018/07/15/springboot/chapter-five/