Spring中@Primary注解的作用詳解
@Primary注解作用詳解
此注解時為了標識哪個Bean是默認的Bean
@Bean
public AMapper aMapper1(AConfig aConfig) {
return new AMapperImpl1(aConfig);
}
@Bean
@Primary
public AMapper aMapper2(AConfig aConfig) {
return new AMapperImpl2(aConfig);
}上述代碼,當存在多個相同類型的Bean注入時,加上@Primary注解,來確定默認的實現(xiàn)標識。
案例
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。
當給指定的組件添加@primary后,默認會注入@Primary的配置組件。
@Component
@Primary
public class Doctor implements Worker {
@Override
public String work() {
return "醫(yī)生工作是治病";
}
}給Doctor 加上@Primary,則默認注入的就是 Doctor 的實現(xiàn)。 瀏覽器訪問:localhost:8080/info

到此這篇關(guān)于Spring中@Primary注解的作用詳解的文章就介紹到這了,更多相關(guān)@Primary注解的作用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot利用@Validated注解優(yōu)雅實現(xiàn)參數(shù)校驗
在開發(fā) Web 應(yīng)用時,用戶輸入的合法性校驗是保障系統(tǒng)穩(wěn)定性的基礎(chǔ),?Spring Boot 的 @Validated 注解 提供了一種更優(yōu)雅的解決方案,下面就跟隨小編一起學(xué)習(xí)一下吧2025-04-04
關(guān)于mybatis的一級緩存和二級緩存的那些事兒
MyBatis自帶的緩存有一級緩存和二級緩存,今天我們就來學(xué)習(xí)一下,文中有非常詳細的總結(jié),對正在學(xué)習(xí)的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06
java?poi之XWPFDocument如何讀取word內(nèi)容并創(chuàng)建新的word
這篇文章主要介紹了java?poi之XWPFDocument如何讀取word內(nèi)容并創(chuàng)建新的word問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

