Spring中@Primary注解的作用詳解
@Primary注解作用詳解
此注解時為了標(biāo)識哪個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)存在多個相同類型的Bean注入時,加上@Primary注解,來確定默認(rèn)的實現(xiàn)標(biāo)識。
案例
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ī)生工作是治病";
}
}
// 啟動,調(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);
}
}上述情況下,一個接口多個實現(xiàn),并且通過@Autowired注入 Worker, 由于@Autowired是通過ByType的形式,來給指定的字段和方法來注入所需的外部資源, 但由于此類有多個實現(xiàn),Spring不知道注入哪個實現(xiàn),所以在啟動的時候會拋出異常。
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)會注入@Primary的配置組件。
@Component
@Primary
public class Doctor implements Worker {
@Override
public String work() {
return "醫(yī)生工作是治病";
}
}給Doctor 加上@Primary,則默認(rèn)注入的就是 Doctor 的實現(xiàn)。 瀏覽器訪問:localhost:8080/info

到此這篇關(guān)于Spring中@Primary注解的作用詳解的文章就介紹到這了,更多相關(guān)@Primary注解的作用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java并發(fā)系列之ReentrantLock源碼分析
這篇文章主要為大家詳細(xì)介紹了Java并發(fā)系列之ReentrantLock源碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-02-02
Maven介紹與配置+IDEA集成Maven+使用Maven命令小結(jié)
Maven是Apache軟件基金會的一個開源項目,是一個優(yōu)秀的項目構(gòu)建管理工具,它用來幫助開發(fā)者管理項目中的 jar,以及 jar 之間的依賴關(guān)系、完成項目的編譯、測試、打包和發(fā)布等工作,本文給大家介紹Maven介紹與配置+IDEA集成Maven+使用Maven命令,感興趣的朋友一起看看吧2024-01-01
SpringCloud Zuul網(wǎng)關(guān)功能實現(xiàn)解析
這篇文章主要介紹了SpringCloud Zuul網(wǎng)關(guān)功能實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03

