quarkus依賴註入之三:用註解選擇註入bean

来源:https://www.cnblogs.com/bolingcavalry/archive/2023/08/01/17589402.html
-Advertisement-
Play Games

### 歡迎訪問我的GitHub > 這裡分類和彙總了欣宸的全部原創(含配套源碼):[https://github.com/zq2599/blog_demos](https://github.com/zq2599/blog_demos) ### 本篇概覽 - 本文是《quarkus依賴註入》系列的第 ...


歡迎訪問我的GitHub

這裡分類和彙總了欣宸的全部原創(含配套源碼):https://github.com/zq2599/blog_demos

本篇概覽

  • 本文是《quarkus依賴註入》系列的第三篇,前文咱們掌握了創建bean的幾種方式,本篇趁熱打鐵,學習一個與創建bean有關的重要知識點:一個介面如果有多個實現類時,bean實例應該如何選擇其中的一個呢?可以用註解來設定bean的選擇邏輯
  • 如果您熟悉spring,此刻應該會想到ConditionalXXX註解,下麵的代碼來自spring官方,註解ConditionalOnProperty的作用是根據配置信息來控制bean是否實例化,本篇咱們要掌握的是quarkus框架下的類似控制邏輯
@Service
@ConditionalOnProperty(
  value="logging.enabled", 
  havingValue = "true", 
  matchIfMissing = true)
class LoggingService {
    // ...
}
  • 本篇主要是通過實例學習以下五個註解的用法
  1. LookupIfProperty,配置項的值符合要求才能使用bean
  2. LookupUnlessProperty,配置項的值不符合要求才能使用bean
  3. IfBuildProfile,如果是指定的profile才能使用bean
  4. UnlessBuildProfile,如果不是指定的profile才能使用bean
  5. IfBuildProperty,如果構建屬性匹配才能使用bean

源碼下載

名稱 鏈接 備註
項目主頁 https://github.com/zq2599/blog_demos 該項目在GitHub上的主頁
git倉庫地址(https) https://github.com/zq2599/blog_demos.git 該項目源碼的倉庫地址,https協議
git倉庫地址(ssh) [email protected]:zq2599/blog_demos.git 該項目源碼的倉庫地址,ssh協議
  • 這個git項目中有多個文件夾,本次實戰的源碼在quarkus-tutorials文件夾下,如下圖紅框
    image-20220312091203116
  • quarkus-tutorials是個父工程,裡面有多個module,本篇實戰的module是basic-di,如下圖紅框
    image-20220312091404031

LookupIfProperty,配置項的值符合要求才能使用bean

  • 註解LookupIfProperty的作用是檢查指定配置項,如果存在且符合要求,才能通過代碼獲取到此bean,
  • 有個關鍵點請註意:下圖是官方定義,可見LookupIfProperty並沒有決定是否實例化beam,它決定的是能否通過代碼取到bean,這個代碼就是Instance<T>來註入,並且用Instance.get方法來獲取

image-20220319083040615

  • 定義一個介面TryLookupIfProperty.java
public interface TryLookupIfProperty {
    String hello();
}
  • 以及兩個實現類,第一個是TryLookupIfPropertyAlpha.java
public class TryLookupIfPropertyAlpha implements TryLookupIfProperty {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 第二個TryLookupIfPropertyBeta.java
public class TryLookupIfPropertyBeta implements TryLookupIfProperty {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 然後就是註解LookupIfProperty的用法了,如下所示,SelectBeanConfiguration是個配置類,裡面有兩個方法用來生產bean,都用註解LookupIfProperty修飾,如果配置項service.alpha.enabled的值等於true,就會執行tryLookupIfPropertyAlpah方法,如果配置項service.beta.enabled的值等於true,就會執行tryLookupIfPropertyBeta方法
package com.bolingcavalry.config;

import com.bolingcavalry.service.TryLookupIfProperty;
import com.bolingcavalry.service.impl.TryLookupIfPropertyAlpha;
import com.bolingcavalry.service.impl.TryLookupIfPropertyBeta;
import io.quarkus.arc.lookup.LookupIfProperty;
import javax.enterprise.context.ApplicationScoped;

public class SelectBeanConfiguration {

    @LookupIfProperty(name = "service.alpha.enabled", stringValue = "true")
    @ApplicationScoped
    public TryLookupIfProperty tryLookupIfPropertyAlpha() {
        return new TryLookupIfPropertyAlpha();
    }

    @LookupIfProperty(name = "service.beta.enabled", stringValue = "true")
    @ApplicationScoped
    public TryLookupIfProperty tryLookupIfPropertyBeta() {
        return new TryLookupIfPropertyBeta();
    }
}
  • 然後來驗證註解LookupIfProperty是否生效,下麵是單元測試代碼,有兩處需要註意的地方,稍後會提到
package com.bolingcavalry;

import com.bolingcavalry.service.TryLookupIfProperty;
import com.bolingcavalry.service.impl.TryLookupIfPropertyAlpha;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

@QuarkusTest
public class BeanInstanceSwitchTest {

    @BeforeAll
    public static void setUp() {
        System.setProperty("service.alpha.enabled", "true");
    }

    // 註意,前面的LookupIfProperty不能決定註入bean是否實力話,只能決定Instance.get是否能取到,
    //所以此處要註入的是Instance,而不是TryLookupIfProperty本身
    @Inject
    Instance<TryLookupIfProperty> service;

    @Test
    public void testTryLookupIfProperty() {
        Assertions.assertEquals("from " + tryLookupIfPropertyAlpha.class.getSimpleName(),
                                service.get().hello());
    }
}

  • 上述代碼有以下兩點要註意
  1. 註意TryLookupIfProperty的註入方式,對這種運行時才能確定具體實現類的bean,要用Instance的方式註入,使用時要用Instance.get方法取得bean
  2. 單元測試的BeforeAll註解用於指定測試前要做的事情,這裡用System.setProperty設置配置項service.alpha.enabled,所以,理論上SelectBeanConfiguration.tryLookupIfPropertyAlpha方法應該會執行,也就是說註入的TryLookupIfProperty應該是TryLookupIfPropertyAlpha實例,所以testTryLookupIfProperty中用assertEquals斷言預測:TryLookupIfProperty.hello的值來自TryLookupIfPropertyAlpha
  • 執行單元測試,如下圖,符合預期

image-20220316090323717

  • 修改BeanInstanceSwitchTest.setUp,將service.alpha.enabled改成service.alpha.enabled,如此理論上SelectBeanConfiguration.tryLookupIfPropertyBeta方法應該會執行,實例化的應該就是TryLookupIfPropertyBeta,那麼本次單元測試就不能通過了
  • 如下圖,果然,註入的實例變成了TryLookupIfPropertyBeta,但是預期的還是之前的TryLookupIfPropertyAlpha,於是測試失敗

image-20220316091510500

LookupUnlessProperty,配置項的值不符合要求才能使用bean

  • LookupIfProperty的意思是配置項的值符合要求才會創建bean,而LookupUnlessProperty恰好相反,意思是配置項的值不符合要求才能使用bean

  • 為了驗證LookupUnlessProperty的效果,修改SelectBeanConfiguration.java,只修改tryLookupIfPropertyBeta方法的註解,由從之前的LookupIfProperty改為LookupUnlessProperty,屬性也改為service.alpha.enabled,現在的邏輯是:如果屬性service.alpha.enabled的值是true,就執行tryLookupIfPropertyAlpha,如果屬性service.alpha.enabled的值不是true,就執行tryLookupIfPropertyBeta

public class SelectBeanConfiguration {

    @LookupIfProperty(name = "service.alpha.enabled", stringValue = "true")
    @ApplicationScoped
    public TryLookupIfProperty tryLookupIfPropertyAlpha() {
        return new TryLookupIfPropertyAlpha();
    }

    @LookupUnlessProperty(name = "service.alpha.enabled", stringValue = "true")
    @ApplicationScoped
    public TryLookupIfProperty tryLookupIfPropertyBeta() {
        return new TryLookupIfPropertyBeta();
    }
}
  • 打開剛纔的BeanInstanceSwitchTest.java,setUp方法中將service.alpha.enabled的值設為true
@BeforeAll
public static void setUp() {
	System.setProperty("service.alpha.enabled", "true");
}
  • 運行單元測試,如下圖,符合預期

image-20220316225710868

  • 現在把service.alpha.enabled的值設為false,單元測試不通過,提示返回值是TryLookupIfPropertyBeta,這也是符合預期的,證明LookupUnlessProperty已經生效了

    image-20220316230306789

  • 此刻您可能會好奇,如果配置項service.alpha.enabled不存在會如何,咱們將setUp方法中的System.setProperty這段代碼刪除,這樣配置項service.alpha.enabled就不存在了,再次執行單元測試,發現SelectBeanConfiguration類的tryLookupIfPropertyAlpha和tryLookupIfPropertyBeta兩個方法都沒有執行,導致沒有TryLookupIfProperty類型的bean

image-20220316231339268

  • 這時候您應該發現了一個問題:如果配置項service.alpha.enabled不存在的時候如何返回一個預設bean,以避免找不到bean呢?

  • LookupIfProperty和LookupUnlessProperty都有名為lookupIfMissing的屬性,意思都一樣:指定配置項不存在的時候,就執行註解所修飾的方法,修改SelectBeanConfiguration.java,如下圖黃框所示,增加lookupIfMissing屬性,指定值為true(沒有指定的時候,預設值是false)

image-20220316231842895

  • 再次運行單元測試,如下圖,儘管service.alpha.enabled不存在,但lookupIfMissing屬性起了作用,SelectBeanConfiguration.tryLookupIfPropertyAlpha方法還是執行了,於是測試通過

image-20220316232218808

IfBuildProfile,如果是指定的profile才能使用bean

  • 應用在運行時,其profile是固定的,IfBuildProfile檢查當前profile是否是指定值,如果是,其修飾的bean就能被業務代碼使用
  • 對比官方對LookupIfProperty和IfBuildProfile描述的差別,LookupIfProperty決定了是否能被選擇,IfBuildProfile決定了是否在容器中
# LookupIfProperty,說的是be obtained by programmatic
Indicates that a bean should only be obtained by programmatic lookup if the property matches the provided value.
# IfBuildProfile,說的是be enabled
the bean will only be enabled if the Quarkus build time profile matches the specified annotation value.
  • 接下來寫代碼驗證,先寫個介面
public interface TryIfBuildProfile {
    String hello();
}
  • 再寫兩個實現類,第一個是TryIfBuildProfileProd.java
public class TryIfBuildProfileProd implements TryIfBuildProfile {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 第二個TryIfBuildProfileDefault.java
public class TryIfBuildProfileDefault implements TryIfBuildProfile {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 再來看IfBuildProfile的用法,在剛纔的SelectBeanConfiguration.java中新增兩個方法,如下所示,應用運行時,如果profile是test,那麼tryIfBuildProfileProd方法會被執行,還要註意的是註解DefaultBean的用法,如果profile不是test,那麼quarkus的bean容器中就沒有TryIfBuildProfile類型的bean了,此時DefaultBean修飾的tryIfBuildProfileDefault方法就會被執行,導致TryIfBuildProfileDefault的實例註冊在quarkus容器中
@Produces
@IfBuildProfile("test")
public TryIfBuildProfile tryIfBuildProfileProd() {
	return new TryIfBuildProfileProd();
}

@Produces
@DefaultBean
public TryIfBuildProfile tryIfBuildProfileDefault() {
	return new TryIfBuildProfileDefault();
}
  • 單元測試代碼寫在剛纔的BeanInstanceSwitchTest.java中,運行單元測試是profile被設置為test,所以tryIfBuildProfile的預期是TryIfBuildProfileProd實例,註意,這裡和前面LookupIfProperty不一樣的是:這裡的TryIfBuildProfile直接註入就好,不需要Instance<T>來註入

    @Inject
    TryIfBuildProfile tryIfBuildProfile;
    
    @Test
    public void testTryLookupIfProperty() {
    	Assertions.assertEquals("from " + TryLookupIfPropertyAlpha.class.getSimpleName(),
                                service.get().hello());
    }
    
    @Test
    public void tryIfBuildProfile() {
    	Assertions.assertEquals("from " + TryIfBuildProfileProd.class.getSimpleName(),
                    tryIfBuildProfile.hello());
    }
    
  • 執行單元測試,如下圖,測試通過,紅框顯示當前profile確實是test

image-20220320101229556

  • 再來試試DefaultBean的是否正常,修改SelectBeanConfiguration.java的代碼,如下圖紅框,將IfBuildProfile註解的值從剛纔的test改為prod,如此一來,再執行單元測試時tryIfBuildProfileProd方法就不會被執行了,此時看tryIfBuildProfileDefault方法能否執行

image-20220318230726955

  • 執行單元測試,結果如下圖,黃框中的內容證明是tryIfBuildProfileDefault方法被執行,也就是說DefaultBean正常工作

image-20220320101353239

UnlessBuildProfile,如果不是指定的profile才能使用bean

  • UnlessBuildProfile的邏輯與IfBuildProfile相反:如果不是指定的profile才能使用bean
  • 回顧剛纔測試失敗的代碼,如下圖紅框,單元測試的profile是test,下麵要求profile必須等於prod,因此測試失敗,現在咱們將紅框中的IfBuildProfile改為UnlessBuildProfile,意思是profile不等於prod的時候bean可以使用

image-20220318230726955

  • 執行單元測試,如下圖,這一次順利通過,證明UnlessBuildProfile的作用符合預期

image-20220320101503515

IfBuildProperty,如果構建屬性匹配才能使用bean

  • 最後要提到註解是IfBuildProperty是,此註解與LookupIfProperty類似,下麵是兩個註解的官方描述對比,可見IfBuildProperty作用的熟悉主要是構建屬性(前面的文章中提到過構建屬性,它們的特點是運行期間只讀,值固定不變)
# LookupIfProperty的描述,如果屬性匹配,則此bean可以被獲取使用
Indicates that a bean should only be obtained by programmatic lookup if the property matches the provided value.
# IfBuildProperty的描述,如果構建屬性匹配,則此bean是enabled
the bean will only be enabled if the Quarkus build time property matches the provided value
  • 限於篇幅,就不寫代碼驗證了,來看看官方demo,用法上與LookupIfProperty類似,可以用DefaultBean來兜底,適配匹配失敗的場景
@Dependent
public class TracerConfiguration {

    @Produces
    @IfBuildProperty(name = "some.tracer.enabled", stringValue = "true")
    public Tracer realTracer(Reporter reporter, Configuration configuration) {
        return new RealTracer(reporter, configuration);
    }

    @Produces
    @DefaultBean
    public Tracer noopTracer() {
        return new NoopTracer();
    }
}
  • 至此,基於多種註解來選擇bean實現的學習已經完成,依靠配置項和profile,已經可以覆蓋多數場景下bean的確認,如果這些不能滿足您的業務需求,接下來的文章咱們繼續瞭解更多靈活的選擇bean的方式

歡迎關註博客園:程式員欣宸

學習路上,你不孤單,欣宸原創一路相伴...


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 在 Protocol Buffers (protobuf) 中,可以使用特定的選項來指定生成的 JSON 標簽。通過在消息定義中使用 `[(json_name)]` 選項,可以控制生成的 JSON 欄位名稱。這樣可以確保 Protocol Buffers 和 JSON 之間的互操作性。 下麵是一個示 ...
  • ## 一、問題是怎麼發現的 最近有個新系統開發完成後要上線,由於系統調用量很大,所以先對核心介面進行了一次壓力測試,由於核心介面中基本上只有純記憶體運算,所以預估核心介面的壓測QPS能夠達到上千。 壓測容器配置:4C8G 先從10個併發開始進行發壓,結果cpu一下就飆升到了100%,但是核心介面的qp ...
  • 編程基礎常識 一、註釋 1、對代碼的說明與解釋,它不會被編譯執行,也不會顯示在編譯結果中 2、註釋分為:單行註釋和多行註釋 3、用#號開始,例如:#這是我的第一個python程式 4、註釋可以寫在單獨一行,也可以寫在一句代碼後面 5、不想執行編譯,又不能刪除的代碼,可以先用#註釋掉,代碼批量註釋用C ...
  • 要解決多線程併發問題,常見的手段無非就幾種。加鎖,如使用synchronized,ReentrantLock,加鎖可以限制資源只能被一個線程訪問;CAS機制,如AtomicInterger,AtomicBoolean等原子類,通過自旋的方式來嘗試修改資源;還有本次我們要介紹的ThreadLocal類 ...
  • MQ(Message Queue)作為一種用於實現非同步通信的技術,具有重要的作用和應用場景。在面試過程中,MQ相關的問題經常被問到,因此瞭解MQ的用途和設計原則是必不可少的。本文總結了MQ的常見面試題,包括MQ的作用、產品選型、消息不丟失的保證、消息消費的冪等性、消息順序的保證、消息的高效讀寫、分佈... ...
  • 狀態機是有限狀態自動機的簡稱,是現實事物運行規則抽象而成的一個數學模型。狀態機,也就是 State Machine ,不是指一臺實際機器,而是指一個數學模型。說白了,一般就是指一張狀態轉換圖。 ...
  • EOF,為End Of File的縮寫,通常在文本的最後存在此字元表示資料結束。 在微軟的DOS和Windows中,讀取數據時終端不會產生EOF。此時,應用程式知道數據源是一個終端(或者其它“字元設備”),並將一個已知的保留的字元或序列解釋為文件結束的指明;最普遍地說,它是ASCII碼中的替換字元( ...
  • 本文介紹了在沒有 Spring Boot 和 Starter 之前,開發人員在使用傳統的 Spring XML 開發 Web 應用時需要引用許多依賴,並且需要大量編寫 XML 代碼來描述 Bean 以及它們之間的依賴關係。也瞭解瞭如何利用 SPI 載入自定義標簽來載入 Bean 併進行註入。 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...