Spring中@Primary注解的作用詳解
@Primary注解作用詳解
此注解時(shí)為了標(biāo)識(shí)哪個(gè)Bean是默認(rèn)的Bean
@Bean
public AMapper aMapper1(AConfig aConfig) {
return new AMapperImpl1(aConfig);
}
@Bean
@Primary
public AMapper aMapper2(AConfig aConfig) {
return new AMapperImpl2(aConfig);
}上述代碼,當(dāng)存在多個(gè)相同類型的Bean注入時(shí),加上@Primary注解,來(lái)確定默認(rèn)的實(shí)現(xiàn)標(biāo)識(shí)。
案例
public interface Worker {
public String work();
}
@Component
public class Singer implements Worker {
@Override
public String work() {
return "歌手的工作是唱歌";
}
}
@Component
public class Doctor implements Worker {
@Override
public String work() {
return "醫(yī)生工作是治病";
}
}
// 啟動(dòng),調(diào)用接口
@SpringBootApplication
@RestController
public class SimpleWebTestApplication {
@Autowired
private Worker worker;
@RequestMapping("/info")
public String getInfo(){
return worker.work();
}
public static void main(String[] args) {
SpringApplication.run(SimpleWebTestApplication.class, args);
}
}上述情況下,一個(gè)接口多個(gè)實(shí)現(xiàn),并且通過(guò)@Autowired注入 Worker, 由于@Autowired是通過(guò)ByType的形式,來(lái)給指定的字段和方法來(lái)注入所需的外部資源, 但由于此類有多個(gè)實(shí)現(xiàn),Spring不知道注入哪個(gè)實(shí)現(xiàn),所以在啟動(dòng)的時(shí)候會(huì)拋出異常。
Consider marking one of the beans as @Primary,
updating the consumer to accept multiple beans,
or using @Qualifier to identify the bean that should be consumed。
當(dāng)給指定的組件添加@primary后,默認(rèn)會(huì)注入@Primary的配置組件。
@Component
@Primary
public class Doctor implements Worker {
@Override
public String work() {
return "醫(yī)生工作是治病";
}
}給Doctor 加上@Primary,則默認(rèn)注入的就是 Doctor 的實(shí)現(xiàn)。 瀏覽器訪問(wèn):localhost:8080/info

到此這篇關(guān)于Spring中@Primary注解的作用詳解的文章就介紹到這了,更多相關(guān)@Primary注解的作用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中 URL實(shí)現(xiàn)斷點(diǎn)下載
Java中 URL實(shí)現(xiàn)斷點(diǎn)下載,需要的朋友可以參考一下2013-03-03
SpringBoot利用@Validated注解優(yōu)雅實(shí)現(xiàn)參數(shù)校驗(yàn)
在開(kāi)發(fā) Web 應(yīng)用時(shí),用戶輸入的合法性校驗(yàn)是保障系統(tǒng)穩(wěn)定性的基礎(chǔ),?Spring Boot 的 @Validated 注解 提供了一種更優(yōu)雅的解決方案,下面就跟隨小編一起學(xué)習(xí)一下吧2025-04-04
在spring中使用自定義注解注冊(cè)監(jiān)聽(tīng)器的方法
本篇文章主要介紹了在spring中使用自定義注解注冊(cè)監(jiān)聽(tīng)器的方法,本文就是在分析監(jiān)聽(tīng)器回調(diào)原理的基礎(chǔ)上,在spring環(huán)境中使用自定義的注解實(shí)現(xiàn)一個(gè)監(jiān)聽(tīng)器。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Java實(shí)現(xiàn)AOP面向切面編程的實(shí)例教程
這篇文章主要介紹了Java實(shí)現(xiàn)AOP面向切面編程的實(shí)例教程,通常Java中的AOP都是利用Spring框架中造好的輪子來(lái)開(kāi)發(fā),而本文則關(guān)注于Java本身AOP的設(shè)計(jì)模式實(shí)現(xiàn),需要的朋友可以參考下2016-04-04
關(guān)于mybatis的一級(jí)緩存和二級(jí)緩存的那些事兒
MyBatis自帶的緩存有一級(jí)緩存和二級(jí)緩存,今天我們就來(lái)學(xué)習(xí)一下,文中有非常詳細(xì)的總結(jié),對(duì)正在學(xué)習(xí)的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06
java?poi之XWPFDocument如何讀取word內(nèi)容并創(chuàng)建新的word
這篇文章主要介紹了java?poi之XWPFDocument如何讀取word內(nèi)容并創(chuàng)建新的word問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2025-04-04

