引言:使用 spring.profiles.active 參數,搭配@Profile注解,可以實現不同環境下(開發、測試、生產)配置參數的切換
一.根據springboot的配置文件命名約定,結合active可在不同環境引用不同的properties外部配置
參考官方文檔:
根據文檔描述,我們除application.properties外,還可以根據命名約定( 命名格式:application-{profile}.properties)來配置,如果active賦予的參數沒有與使用該命名約定格式文件相匹配的話,app則會默認從名為application-default.properties 的配置文件加載配置。
如:spring.profiles.active=hello-world,sender,dev 有三個參數,其中 dev 正好匹配下面配置中的application-dev.properties 配置文件,所以app啟動時,項目會先從application-dev.properties加載配置,再從application.properties配置文件加載配置,如果有重復的配置,則會以application.properties的配置為准。(配置文件加載順序詳見官方文檔:24. Externalized Configuration)
如此,我們就不用為了不同的運行環境而去更改大量的環境配置了(此處,dev、pro、test分別為:開發、生產、測試環境配置)
二.通過@Profile注解匹配active參數,動態加載內部配置
參考官方文檔:
1.@Profile注解使用范圍:@Configration 和 @Component 注解的類及其方法,其中包括繼承了@Component的注解:@Service、@Controller、@Repository等…
2.@Profile可接受一個或者多個參數,例如:
@Profile({"tut1","hello-world"}) @Configuration public class Tut1Config { @Bean public Queue hello() { return new Queue("hello"); } @Profile("receiver") @Bean public Tut1Receiver receiver() { return new Tut1Receiver(); } @Profile("sender") @Bean public Tut1Sender sender() { return new Tut1Sender(); } }
當 spring.profiles.active=hello-world,sender 時,該配置類生效,且第一個@Bean和第三個@Bean生效
如果spring.profiles.active=hello-world ,則該配置文件生效,第一個@Bean生效
如果spring.profiles.active=sender ,該配置文件未生效,所以下面的@Bean都不會生效
如此,當我們的項目需要運行在不同環境,特異化配置又比較多,該注解的優勢是相當明顯的!
---------------------
作者:sword6
來源:CSDN
原文:https://blog.csdn.net/swordsnapliu/article/details/78540902
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!