Spring中@Autowire注入的深入講解
一直在思考spring的@Autowire注入屬性時(shí)到底是按類型注入還是按名稱注入,今天寫了一個(gè)測(cè)試來(lái)證明一下。
定義接口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(); }}
編寫測(cè)試類:
@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()方法中會(huì)執(zhí)行后置處理器AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues() ,繼續(xù)跟蹤,在DefaultListableBeanFactory.doResolveDependency()方法中的findAutowireCandidates()根據(jù)類型匹配到兩個(gè)Bean,見(jiàn)截圖:
由于獲取的Bean超過(guò)兩個(gè),spring會(huì)根據(jù)名稱去匹配,如果匹配成功則返回對(duì)應(yīng)的bean;如果匹配失敗,則會(huì)拋出異常。如圖:
到此為止,我們已經(jīng)能發(fā)現(xiàn)@Autowire注解注入屬性的原理:先根據(jù)類型注入,如果獲取到多個(gè)Bean,則根據(jù)名稱匹配,若名稱未匹配上就拋出異常。
總結(jié)
到此這篇關(guān)于Spring中@Autowire注入的文章就介紹到這了,更多相關(guān)Spring中@Autowire注入內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Springboot 全局日期格式化處理的實(shí)現(xiàn)2. vue實(shí)現(xiàn)web在線聊天功能3. Django使用HTTP協(xié)議向服務(wù)器傳參方式小結(jié)4. JAMon(Java Application Monitor)備忘記5. SpringBoot+TestNG單元測(cè)試的實(shí)現(xiàn)6. docker容器調(diào)用yum報(bào)錯(cuò)的解決辦法7. Java使用Tesseract-Ocr識(shí)別數(shù)字8. 完美解決vue 中多個(gè)echarts圖表自適應(yīng)的問(wèn)題9. HTML基本語(yǔ)法和語(yǔ)義寫法規(guī)則與實(shí)例10. 前端獲取http狀態(tài)碼400的返回值實(shí)例
