1. 程式人生 > >使用 spring.profiles.active 及 @profile 註解 動態化配置內部及外部配置

使用 spring.profiles.active 及 @profile 註解 動態化配置內部及外部配置

引言:使用 spring.profiles.active 引數,搭配@Profile註解,可以實現不同環境下(開發、測試、生產)配置引數的切換

一.根據springboot的配置檔案命名約定,結合active可在不同環境引用不同的properties外部配置

參考官方文件:
springboot官方文件截圖
根據文件描述,我們除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)
 springboot外部配置


如此,我們就不用為了不同的執行環境而去更改大量的環境配置了(此處,dev、pro、test分別為:開發、生產、測試環境配置)

二.通過@Profile註解匹配active引數,動態載入內部配置
參考官方文件:
springboot官方文件截圖

[email protected]註解使用範圍:@Configration 和 @Component 註解的類及其方法,其中包括繼承了@Component的註解:@Service、@Controller、@Repository等…
[email protected]可接受一個或者多個引數,例如:

@Profile({"tut1","hello-world"
}) @Configuration public class Tut1Config { @Bean publicQueuehello() { return newQueue("hello"); } @Profile("receiver") @Bean publicTut1Receiverreceiver() { return newTut1Receiver(); } @Profile("sender") @Bean publicTut1Sendersender() { return
newTut1Sender(); } }

當 spring.profiles.active=hello-world,sender 時,該配置類生效,且第一個@Bean和第三個@Bean生效
如果spring.profiles.active=hello-world ,則該配置檔案生效,第一個@Bean生效
如果spring.profiles.active=sender ,該配置檔案未生效,所以下面的@Bean都不會生效
如此,當我們的專案需要執行在不同環境,特異化配置又比較多,該註解的優勢是相當明顯的!

[email protected] 註解取反
請看下面程式碼:

@Component
public class Tut1CommindLineRunner {
    @Profile("usage_message")
    @Bean
    publicCommandLineRunnerusage() {
        return strings -> {
            System.out.println("This app uses Spring Profiles to control its behavior.\n");
            System.out.println("Sample usage: java -jar rabbit-tutorials.jar --spring.profiles.active=hello-world,sender");
        };
    }
    @Profile("!usage_message")
    @Bean
    publicCommandLineRunnertutorial() {
        return newRabbitAmqpTutorialsRunner();
    }
}

該@Profile註解接收了兩個類似於取反一樣的配置引數,該用法我沒有找到相關的官方文件,這是在rabbitmq官網,關於springboot amqp 的一段程式碼。
通過檢視原始碼,我發現,其實這個就是一個類似於取反的意思,這裡理解為:匹配不上該配置引數的時候,啟用該配置,相關原始碼:

package org.springframework.core.env;
//...
public abstract classAbstractEnvironmentimplementsConfigurableEnvironment {
    //...
    public booleanacceptsProfiles(String... profiles) {
        Assert.notEmpty(profiles,"Must specify at least one profile");
        String[] var2 = profiles;
        int var3 = profiles.length;
        for(intvar4 =0;var4 < var3;++var4) {
            String profile = var2[var4];
            if(StringUtils.hasLength(profile) && profile.charAt(0) == 33) {
                if(!this.isProfileActive(profile.substring(1))) {
                    return true;
                }
            } else if(this.isProfileActive(profile)) {
                return true;
            }
        }
        return false;
    }

    protected booleanisProfileActive(String profile) {
        this.validateProfile(profile);
        Set<String> currentActiveProfiles =this.doGetActiveProfiles();
        return currentActiveProfiles.contains(profile) || currentActiveProfiles.isEmpty() &&this.doGetDefaultProfiles().contains(profile);
    }
    //...
}

“!”對應的char 編碼為:33
此處:StringUtils.hasLength(profile) && profile.charAt(0) == 33 ,如果配置以 “!”開頭,則將“!”後的字串與配置進行匹配,並取反,如果為true,則返回true,即active沒有配置該配置引數,則返回true,即啟動該配置。

如有理解錯誤或者描述不正確的地方,歡迎留言!

相關推薦

使用 spring.profiles.active @profile 註解 動態化配置內部外部配置

引言:使用 spring.profiles.active 引數,搭配@Profile註解,可以實現不同環境下(開發、測試、生產)配置引數的切換 一.根據springboot的配置檔案命名約定,結合active可在不同環境引用不同的properties外部配置

SpringBoot application.yml logback.xml,多環境配置,支持 java -jar --spring.profiles.active

ole att code nio nec 支持 啟動 level -s 趁今天有時間整理了一下 啟動命令為 //開發環境 java -jar app.jar --spring.profiles.active=dev--server.port=8060 //測

spring.profiles.active 針對多種啟動環境的spring配置

ttr 配置使用 log nbsp files location .profile 環境 param 使用spring.profiles.active 配置正式環境,測試環境 配置方式: 1、在spring配置文件中配置兩種環境信息   <beans profile=

spring-boot:run啟動時,指定spring.profiles.active

Maven啟動指定Profile通過-P,如mvn spring-boot:run -Ptest,但這是Maven的Profile。 如果要指定spring-boot的spring.profiles.active,則必須使用mvn spring-boot:run -Drun.profiles=test 如

spring.profiles.active在專案中獲取引數

<!-- 環境切換專用: dev 開發環境  test:測試環境  prod:正式環境 --> <context-param> <param-name>spring.profiles.active</param-name>

mysql 配置了環境服務 cmd不在內部外部命令 解決方法

1.mysql出現錯誤 一般先去看環境變數配置了沒有eg:C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin2.如果配置了環境變數,請搜尋服務,開啟或者重啟mysql服務3.前面倆種都配置了還是連線不上eg: mysql -

Spring介紹配置(XML文件配置註解配置)

處理 tis 配置文件 3.0 span 特點 inverse logging 結構 本節內容: Spring介紹 Spring搭建 Spring概念 Spring配置講解 使用註解配置Spring 一、Spring介紹 1. 什麽是Spring

Spring MVC 配置應用 註解配置(2)

SpringMVC 註解應用 /login.do 具體的步驟 -->DispatcherServlet -->HandlerMapping -->LoginController  -->ViewReslover -->login.jsp (1)&

Java框架-Spring基於註解的IOC配置註解

註解配置與xml配置都實現了減低程式間耦合的功能。 不同公司由不同習慣,有可能是純xml、純註解(很少)或者xml與註解混合使用(基於註解的IOC配置)。 1. 基於註解的IOC配置 1.1 建立一個簡單案例 1.1.1 建立專案,新增依賴(pom.xml)

Spring註解配置Mongo基本CRUD操作簡介

Mongo安裝配置參考基本操作等可參考http://www.runoob.com/mongodb/mongodb-tutorial.html,其中help()方法十分實用,可以不用讓使用者不用記太多方法,如help.collection.help()會顯示集合(相當於傳統資料庫中的的表)的所有方

spring mvc @Transactional 註解 配置 步驟 @Transactional 事物無效 注意事項

spring-context.xml檔案配置 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xs

Spring原始碼解析 – @Configuration配置註解Bean的解析

  在分析Spring 容器建立過程時,我們知道容器預設會載入一些後置處理器PostPRocessor,以AnnotationConfigApplicationContext為例,在建構函式中初始化reader時,載入預設後置處理器。其中 ConfigurationClassPostProcessor這個後置

Spring學習6(5):FactoryBean使用註解配置

Spring學習6(5) FactoryBean  Spring通過反射機制利用<bean>的class屬性來指定實現類的方法在Bean的例項化過程較為複雜時會增加編碼繁瑣度。故此Spring提供了一個org.springframework.bean

spring事務的傳播屬性和事務隔離級別配置事務(註解方式)

一、Propagation (事務的傳播屬性) Propagation :  key屬性確定代理應該給哪個方法增加事務行為。這樣的屬性最重要的部份是傳播行為。有以下選項可供使用:   PROPAGATION_REQUIRED--支援當前事務,如果當前沒有事務,就新建一個事務。這是最常見的選擇。 PROPAG

spring MVC配置說明Controller註解例項

<!-- Spring MVC配置 --> <!-- ====================================== --> <servlet> <servlet-name>spring</servlet-name>

spring配置ioc註解總結

目前都是用springboot來解決一些日常需求,有一段時間沒用springmvc了,在這裡總結一下,當作回顧。同時,springmvc也是java後臺的基礎,值得複習。 bean中的一些配置 sc

Spring】使用@Profile註解實現開發、測試和生產環境的配置和切換,看完這篇我徹底會了!!

## 寫在前面 > 在實際的企業開發環境中,往往都會將環境分為:開發環境、測試環境和生產環境,而每個環境基本上都是互相隔離的,也就是說,開發環境、測試環境和生產環境是互不相通的。在以前的開發過程中,如果開發人員完成相應的功能模組並通過單元測試後,會通過手動修改配置檔案的形式,將專案的配置修改成測試環境

SpringMVC原理註解配置詳解

ges 控制器 sof 靈活 size 實現 query -c requests 1. Spring介紹   Spring MVC是Spring提供的一個強大而靈活的web框架。借助於註解,Spring MVC提供了幾乎是POJO的開發模式,使得控制器的開發和測試更加簡單

Spring完全基於Java和註解配置

進行 要點 servle containe one targe 引入 logs pos 要點: 配置繼承WebApplicationInitializer的類作為啟動類,相當於配置web.xml文件 使用@Configuration註解一個類,在類中的方式使用@Bean註

Spring@Profile註解

logs nbsp clas gpo post pri class .html shu 他山之石 https://www.jianshu.com/p/948c303b2253 https://www.cnblogs.com/chenpi/p/6213849.html Sp