Spring中@Autowire注入的深入講解
一直在思考spring的@Autowire注入屬性時(shí)到底是按類型注入還是按名稱注入,今天寫(xiě)了一個(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(); }}
編寫(xiě)測(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. 解決python腳本中error: unrecognized arguments: True錯(cuò)誤2. PHP8.0新功能之Match表達(dá)式的使用3. Nginx+php配置文件及原理解析4. 解決Python 進(jìn)程池Pool中一些坑5. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究6. Android實(shí)現(xiàn)觸發(fā)html頁(yè)面的Button控件點(diǎn)擊事件方式7. ajax請(qǐng)求添加自定義header參數(shù)代碼8. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼9. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)10. 八種Vue組件間通訊方式合集(推薦)
