Spring中@Autowire注入的深入講解
一直在思考spring的@Autowire注入屬性時到底是按類型注入還是按名稱注入,今天寫了一個測試來證明一下。
定義接口TestService
public interface TestService {
void test();
}
定義接口實現(xiàn):TestServiceImpl1和TestServiceImpl2
@Service
public class TestServiceImpl1 implements TestService {
public void test() {
System.out.println(1111);
}
}
@Service
public class TestServiceImpl2 implements TestService {
public void test() {
System.out.println(2222);
}
}
定義一個bean依賴TestService,
@Controller
public class TestController {
//此時的beanBame=testService
@Autowired
TestService testService;
public void test(){
testService.test();
}
}
編寫測試類:
@Configuration
@ComponentScan("test")
public class Test {
public static void main(String[] args) {
AnnotationConfigApplicationContext context=new AnnotationConfigApplicationContext();
context.register(Test.class);
context.refresh();
TestService bean = context.getBean(TestService.class);
bean.test();
}
}
啟動項目跟蹤源碼:在spring工廠初始化Bean填充屬性的時候,AbstractAutowireCapableBeanFactory.populateBean()方法中會執(zhí)行后置處理器AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() ,繼續(xù)跟蹤,在DefaultListableBeanFactory.doResolveDependency()方法中的findAutowireCandidates()根據(jù)類型匹配到兩個Bean,見截圖:

由于獲取的Bean超過兩個,spring會根據(jù)名稱去匹配,如果匹配成功則返回對應的bean;如果匹配失敗,則會拋出異常。如圖:

到此為止,我們已經(jīng)能發(fā)現(xiàn)@Autowire注解注入屬性的原理:先根據(jù)類型注入,如果獲取到多個Bean,則根據(jù)名稱匹配,若名稱未匹配上就拋出異常。
總結(jié)
到此這篇關(guān)于Spring中@Autowire注入的文章就介紹到這了,更多相關(guān)Spring中@Autowire注入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳談鎖和監(jiān)視器之間的區(qū)別_Java并發(fā)
下面小編就為大家?guī)硪黄斦勬i和監(jiān)視器之間的區(qū)別_Java并發(fā)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
深入理解Java中的并發(fā)工具類CountDownLatch
CountDownLatch?作為?Java?中的一個同步工具類,用于在多線程間實現(xiàn)協(xié)調(diào)和控制,本文主要來和大家講解一下JUC?工具類?CountDownLatch的使用,需要的可以參考一下2023-07-07
Java畢業(yè)設計實戰(zhàn)之二手書商城系統(tǒng)的實現(xiàn)
這是一個使用了java+JSP+Springboot+maven+mysql+ThymeLeaf+FTP開發(fā)的二手書商城系統(tǒng),是一個畢業(yè)設計的實戰(zhàn)練習,具有在線書城該有的所有功能,感興趣的朋友快來看看吧2022-01-01
spring-data-redis自定義實現(xiàn)看門狗機制
redission看門狗機制是解決分布式鎖的續(xù)約問題,本文主要介紹了spring-data-redis自定義實現(xiàn)看門狗機制,具有一定的參考價值,感興趣的可以了解一下2024-03-03

