自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Quarkus依賴注入:用注解選擇注入Bean

開發(fā) 前端
本篇學(xué)習(xí)一個(gè)與創(chuàng)建Bean有關(guān)的重要知識(shí)點(diǎn):一個(gè)接口如果有多個(gè)實(shí)現(xiàn)類時(shí),Bean實(shí)例應(yīng)該如何選擇其中的一個(gè)呢?可以用注解來設(shè)定Bean的選擇邏輯。

本篇概覽

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

源碼下載

  • 本篇實(shí)戰(zhàn)的完整源碼可在GitHub下載到,地址和鏈接信息如下表所示(https://github.com/zq2599/blog_demos)。

  • 這個(gè)git項(xiàng)目中有多個(gè)文件夾,本次實(shí)戰(zhàn)的源碼在quarkus-tutorials文件夾下,如下圖紅框。

  • quarkus-tutorials是個(gè)父工程,里面有多個(gè)module,本篇實(shí)戰(zhàn)的module是basic-di,如下圖紅框。

LookupIfProperty,配置項(xiàng)的值符合要求才能使用bean

  • 注解LookupIfProperty的作用是檢查指定配置項(xiàng),如果存在且符合要求,才能通過代碼獲取到此bean。
  • 有個(gè)關(guān)鍵點(diǎn)請注意:下圖是官方定義,可見LookupIfProperty并沒有決定是否實(shí)例化beam,它決定的是能否通過代碼取到bean,這個(gè)代碼就是Instance<T>來注入,并且用Instance.get方法來獲取。

  • 定義一個(gè)接口TryLookupIfProperty.java。
public interface TryLookupIfProperty {
    String hello();
}
  • 以及兩個(gè)實(shí)現(xiàn)類,第一個(gè)是TryLookupIfPropertyAlpha.java。
public class TryLookupIfPropertyAlpha implements TryLookupIfProperty {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 第二個(gè)TryLookupIfPropertyBeta.java。
public class TryLookupIfPropertyBeta implements TryLookupIfProperty {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 然后就是注解LookupIfProperty的用法了,如下所示,SelectBeanConfiguration是個(gè)配置類,里面有兩個(gè)方法用來生產(chǎn)bean,都用注解LookupIfProperty修飾,如果配置項(xiàng)service.alpha.enabled的值等于true,就會(huì)執(zhí)行tryLookupIfPropertyAlpah方法,如果配置項(xiàng)service.beta.enabled的值等于true,就會(huì)執(zhí)行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();
    }
}
  • 然后來驗(yàn)證注解LookupIfProperty是否生效,下面是單元測試代碼,有兩處需要注意的地方,稍后會(huì)提到。
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是否實(shí)力話,只能決定Instance.get是否能取到,
    //所以此處要注入的是Instance,而不是TryLookupIfProperty本身
    @Inject
    Instance<TryLookupIfProperty> service;

    @Test
    public void testTryLookupIfProperty() {
        Assertions.assertEquals("from " + tryLookupIfPropertyAlpha.class.getSimpleName(),
                                service.get().hello());
    }
}
  • 上述代碼有以下兩點(diǎn)要注意。
  1. 注意TryLookupIfProperty的注入方式,對這種運(yùn)行時(shí)才能確定具體實(shí)現(xiàn)類的bean,要用Instance的方式注入,使用時(shí)要用Instance.get方法取得bean。
  2. 單元測試的BeforeAll注解用于指定測試前要做的事情,這里用System.setProperty設(shè)置配置項(xiàng)service.alpha.enabled,所以,理論上SelectBeanConfiguration.tryLookupIfPropertyAlpha方法應(yīng)該會(huì)執(zhí)行,也就是說注入的TryLookupIfProperty應(yīng)該是TryLookupIfPropertyAlpha實(shí)例,所以testTryLookupIfProperty中用assertEquals斷言預(yù)測:TryLookupIfProperty.hello的值來自TryLookupIfPropertyAlpha。
  • 執(zhí)行單元測試,如下圖,符合預(yù)期。

  • 修改BeanInstanceSwitchTest.setUp,將service.alpha.enabled改成service.alpha.enabled,如此理論上SelectBeanConfiguration.tryLookupIfPropertyBeta方法應(yīng)該會(huì)執(zhí)行,實(shí)例化的應(yīng)該就是TryLookupIfPropertyBeta,那么本次單元測試就不能通過了。
  • 如下圖,果然,注入的實(shí)例變成了TryLookupIfPropertyBeta,但是預(yù)期的還是之前的TryLookupIfPropertyAlpha,于是測試失敗。

LookupUnlessProperty,配置項(xiàng)的值不符合要求才能使用bean

  • LookupIfProperty的意思是配置項(xiàng)的值符合要求才會(huì)創(chuàng)建bean,而LookupUnlessProperty恰好相反,意思是配置項(xiàng)的值不符合要求才能使用bean。
  • 為了驗(yàn)證LookupUnlessProperty的效果,修改SelectBeanConfiguration.java,只修改tryLookupIfPropertyBeta方法的注解,由從之前的LookupIfProperty改為LookupUnlessProperty,屬性也改為service.alpha.enabled,現(xiàn)在的邏輯是:如果屬性service.alpha.enabled的值是true,就執(zhí)行tryLookupIfPropertyAlpha,如果屬性service.alpha.enabled的值不是true,就執(zhí)行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的值設(shè)為true。
@BeforeAll
public static void setUp() {
	System.setProperty("service.alpha.enabled", "true");
}
  • 運(yùn)行單元測試,如下圖,符合預(yù)期。

  • 現(xiàn)在把service.alpha.enabled的值設(shè)為false,單元測試不通過,提示返回值是TryLookupIfPropertyBeta,這也是符合預(yù)期的,證明LookupUnlessProperty已經(jīng)生效了。

  • 此刻您可能會(huì)好奇,如果配置項(xiàng)service.alpha.enabled不存在會(huì)如何,咱們將setUp方法中的System.setProperty這段代碼刪除,這樣配置項(xiàng)service.alpha.enabled就不存在了,再次執(zhí)行單元測試,發(fā)現(xiàn)SelectBeanConfiguration類的tryLookupIfPropertyAlpha和tryLookupIfPropertyBeta兩個(gè)方法都沒有執(zhí)行,導(dǎo)致沒有TryLookupIfProperty類型的bean。

  • 這時(shí)候您應(yīng)該發(fā)現(xiàn)了一個(gè)問題:如果配置項(xiàng)service.alpha.enabled不存在的時(shí)候如何返回一個(gè)默認(rèn)bean,以避免找不到bean呢?
  • LookupIfProperty和LookupUnlessProperty都有名為lookupIfMissing的屬性,意思都一樣:指定配置項(xiàng)不存在的時(shí)候,就執(zhí)行注解所修飾的方法,修改SelectBeanConfiguration.java,如下圖黃框所示,增加lookupIfMissing屬性,指定值為true(沒有指定的時(shí)候,默認(rèn)值是false)。

  • 再次運(yùn)行單元測試,如下圖,盡管service.alpha.enabled不存在,但lookupIfMissing屬性起了作用,SelectBeanConfiguration.tryLookupIfPropertyAlpha方法還是執(zhí)行了,于是測試通過。

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

  • 應(yīng)用在運(yùn)行時(shí),其profile是固定的,IfBuildProfile檢查當(dāng)前profile是否是指定值,如果是,其修飾的bean就能被業(yè)務(wù)代碼使用。
  • 對比官方對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.
  • 接下來寫代碼驗(yàn)證,先寫個(gè)接口。
public interface TryIfBuildProfile {
    String hello();
}
  • 再寫兩個(gè)實(shí)現(xiàn)類,第一個(gè)是TryIfBuildProfileProd.java。
public class TryIfBuildProfileProd implements TryIfBuildProfile {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 第二個(gè)TryIfBuildProfileDefault.java。
public class TryIfBuildProfileDefault implements TryIfBuildProfile {
    @Override
    public String hello() {
        return "from " + this.getClass().getSimpleName();
    }
}
  • 再來看IfBuildProfile的用法,在剛才的SelectBeanConfiguration.java中新增兩個(gè)方法,如下所示,應(yīng)用運(yùn)行時(shí),如果profile是test,那么tryIfBuildProfileProd方法會(huì)被執(zhí)行,還要注意的是注解DefaultBean的用法,如果profile不是test,那么quarkus的bean容器中就沒有TryIfBuildProfile類型的bean了,此時(shí)DefaultBean修飾的tryIfBuildProfileDefault方法就會(huì)被執(zhí)行,導(dǎo)致TryIfBuildProfileDefault的實(shí)例注冊在quarkus容器中。
@Produces
@IfBuildProfile("test")
public TryIfBuildProfile tryIfBuildProfileProd() {
	return new TryIfBuildProfileProd();
}

@Produces
@DefaultBean
public TryIfBuildProfile tryIfBuildProfileDefault() {
	return new TryIfBuildProfileDefault();
}
  • 單元測試代碼寫在剛才的BeanInstanceSwitchTest.java中,運(yùn)行單元測試是profile被設(shè)置為test,所以tryIfBuildProfile的預(yù)期是TryIfBuildProfileProd實(shí)例,注意,這里和前面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());
}
  • 執(zhí)行單元測試,如下圖,測試通過,紅框顯示當(dāng)前profile確實(shí)是test。

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

  • 執(zhí)行單元測試,結(jié)果如下圖,黃框中的內(nèi)容證明是tryIfBuildProfileDefault方法被執(zhí)行,也就是說DefaultBean正常工作。

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

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

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

IfBuildProperty,如果構(gòu)建屬性匹配才能使用bean

  • 最后要提到注解是IfBuildProperty是,此注解與LookupIfProperty類似,下面是兩個(gè)注解的官方描述對比,可見IfBuildProperty作用的熟悉主要是構(gòu)建屬性(前面的文章中提到過構(gòu)建屬性,它們的特點(diǎn)是運(yùn)行期間只讀,值固定不變)。
# LookupIfProperty的描述,如果屬性匹配,則此bean可以被獲取使用
Indicates that a bean should only be obtained by programmatic lookup if the property matches the provided value.
# IfBuildProperty的描述,如果構(gòu)建屬性匹配,則此bean是enabled
the bean will only be enabled if the Quarkus build time property matches the provided value
  • 限于篇幅,就不寫代碼驗(yàn)證了,來看看官方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實(shí)現(xiàn)的學(xué)習(xí)已經(jīng)完成,依靠配置項(xiàng)和profile,已經(jīng)可以覆蓋多數(shù)場景下bean的確認(rèn),如果這些不能滿足您的業(yè)務(wù)需求,接下來的文章咱們繼續(xù)了解更多靈活的選擇bean的方式。
責(zé)任編輯:姜華 來源: 今日頭條
相關(guān)推薦

2023-06-27 08:58:13

quarkusBean

2023-06-29 08:32:41

Bean作用域

2016-03-21 17:08:54

Java Spring注解區(qū)別

2023-10-07 08:35:07

依賴注入Spring

2011-05-31 10:00:21

Android Spring 依賴注入

2022-12-29 08:54:53

依賴注入JavaScript

2017-08-16 16:00:05

PHPcontainer依賴注入

2021-06-03 07:55:12

技術(shù)

2011-04-15 09:44:45

Spring

2009-06-15 17:48:32

Spring注解注入屬性

2016-10-20 19:36:01

androiddagger2依賴注入

2024-12-30 12:00:00

.NET Core依賴注入屬性注入

2019-09-18 18:12:57

前端javascriptvue.js

2022-04-30 08:50:11

控制反轉(zhuǎn)Spring依賴注入

2015-09-02 11:22:36

JavaScript實(shí)現(xiàn)思路

2024-04-01 00:02:56

Go語言代碼

2024-05-27 00:13:27

Go語言框架

2025-01-13 00:13:59

VSCode架構(gòu)依賴注入

2022-04-11 09:02:18

Swift依賴注

2014-07-08 14:05:48

DaggerAndroid依賴
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)