Spring中@Autowire注入的深入講解
一直在思考spring的@Autowire注入屬性時(shí)到底是按類型注入還是按名稱注入,今天寫了一個(gè)測試來證明一下。
定義接口TestService
public interface TestService { void test();}
定義接口實(shí)現(xiàn):TestServiceImpl1和TestServiceImpl2
@Servicepublic class TestServiceImpl1 implements TestService { public void test() { System.out.println(1111); }}
@Servicepublic class TestServiceImpl2 implements TestService { public void test() { System.out.println(2222); }}
定義一個(gè)bean依賴TestService,
@Controllerpublic class TestController {//此時(shí)的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(); }}
啟動(dòng)項(xiàng)目跟蹤源碼:在spring工廠初始化Bean填充屬性的時(shí)候,AbstractAutowireCapableBeanFactory.populateBean()方法中會執(zhí)行后置處理器AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() ,繼續(xù)跟蹤,在DefaultListableBeanFactory.doResolveDependency()方法中的findAutowireCandidates()根據(jù)類型匹配到兩個(gè)Bean,見截圖:

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

到此為止,我們已經(jīng)能發(fā)現(xiàn)@Autowire注解注入屬性的原理:先根據(jù)類型注入,如果獲取到多個(gè)Bean,則根據(jù)名稱匹配,若名稱未匹配上就拋出異常。
總結(jié)
到此這篇關(guān)于Spring中@Autowire注入的文章就介紹到這了,更多相關(guān)Spring中@Autowire注入內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 使用Python webdriver圖書館搶座自動(dòng)預(yù)約的正確方法2. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題3. ASP基礎(chǔ)知識VBScript基本元素講解4. Linux刪除系統(tǒng)自帶版本Python過程詳解5. Python 合并拼接字符串的方法6. Python3 json模塊之編碼解碼方法講解7. Python sublime安裝及配置過程詳解8. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條9. python 使用事件對象asyncio.Event來同步協(xié)程的操作10. python為什么叫爬蟲?

網(wǎng)公網(wǎng)安備