一直在思考spring的@Autowire注入屬性時(shí)到底是按類型注入還是按名稱注入,今天寫(xiě)了一個(gè)測(cè)試來(lái)證明一下。
定義接口TestService
1
2
3
|
public interface TestService { void test(); } |
定義接口實(shí)現(xiàn):TestServiceImpl1和TestServiceImpl2
1
2
3
4
5
6
7
|
@Service public class TestServiceImpl1 implements TestService { public void test() { System.out.println( 1111 ); } } |
1
2
3
4
5
6
7
|
@Service public class TestServiceImpl2 implements TestService { public void test() { System.out.println( 2222 ); } } |
定義一個(gè)bean依賴TestService,
1
2
3
4
5
6
7
8
9
10
|
@Controller public class TestController { //此時(shí)的beanBame=testService @Autowired TestService testService; public void test(){ testService.test(); } } |
編寫(xiě)測(cè)試類:
1
2
3
4
5
6
7
8
9
10
11
|
@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ù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_39600860/article/details/108678305