Spring @Primary和@Qualifier注解原理解析
一 前言
本篇內(nèi)容主要是講解2個(gè)重要的注解使用方式和場(chǎng)景,@Primary,@Qualifier注解;其作用就是消除bean注入時(shí)的歧義,能夠讓spring容器知道加載哪個(gè)bean;
知識(shí)追尋者(Inheriting the spirit of open source, Spreading technology knowledge;)
二 實(shí)現(xiàn)方式
如下示例中使用被單接口Sheet, 實(shí)現(xiàn)類為SheetA , SHeetB ; 由于注入容器時(shí)都是 Sheet類型,會(huì)發(fā)生異常,此時(shí)就是使用@Primary或者@Qualifier對(duì)注入的bean進(jìn)行限制,即可實(shí)現(xiàn)正常注入;
2.1 被單接口
/** * @Author lsc * <p> 被單</p> */public interface Sheet { String getColor();}
2.2 被單實(shí)現(xiàn)類
實(shí)現(xiàn)類A
重寫getColor()方法;輸出red
/** * @Author lsc * <p> </p> */public class SheetA implements Sheet { public String getColor() { return 'red'; }}
實(shí)現(xiàn)類B
重寫getColor()方法;輸出pink
/** * @Author lsc * <p> </p> */public class SheetB implements Sheet { public String getColor() { return 'pink'; }}
2.3 配置類
@Configurationpublic class SheetConfig { @Bean public Sheet sheetA(){ return new SheetA(); } @Bean public Sheet sheetB(){ return new SheetB(); }}
2.4 測(cè)試類
/** * @Author lsc * <p> </p> */@RunWith(SpringJUnit4ClassRunner.class)//創(chuàng)建spring應(yīng)用上下文@ContextConfiguration(classes= {SheetConfig.class})//加載配置類public class SheetTest { @Autowired Sheet sheet; @Test public void sheetTest(){ // System.out.println(sheet.getColor()); }}
測(cè)試會(huì)報(bào)異常,原因是向spring容器注入了2個(gè)Sheet,無法區(qū)分是SheetA 還是 SheetB,所以會(huì)造成bean的歧義問題;
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException:
解決辦法一
在注入的bean上添加@Primary注解;示例如下,此時(shí)向sheetB上添加@Primary注解,spring掃碼注入bean時(shí)優(yōu)先注入帶有@Primary注解的bean;測(cè)試輸出結(jié)果為pink
@Bean@Primarypublic Sheet sheetB(){return new SheetB();}
解決辦法二
注入bean時(shí)添加@Qualifier注解,限定注入的Bean;此時(shí)輸出就是red
@Qualifier('sheetA')//限定注入Bean ID@AutowiredSheet sheet;
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php測(cè)試程序運(yùn)行速度和頁面執(zhí)行速度的代碼2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創(chuàng)建項(xiàng)目的過程8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究
