一直在思考spring的@Autowire注入屬性時到底是按類型注入還是按名稱注入,今天寫了一個測試來證明一下。
定義接口TestService
1
2
3
|
public interface TestService { void test(); } |
定義接口實現: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 ); } } |
定義一個bean依賴TestService,
1
2
3
4
5
6
7
8
9
10
|
@Controller public class TestController { //此時的beanBame=testService @Autowired TestService testService; public void test(){ testService.test(); } } |
編寫測試類:
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(); } } |
啟動項目跟蹤源碼:在spring工廠初始化Bean填充屬性的時候,AbstractAutowireCapableBeanFactory.populateBean()
方法中會執行后置處理器AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues()
,繼續跟蹤,在DefaultListableBeanFactory.doResolveDependency()
方法中的findAutowireCandidates()
根據類型匹配到兩個Bean,見截圖:
由于獲取的Bean超過兩個,spring會根據名稱去匹配,如果匹配成功則返回對應的bean;如果匹配失敗,則會拋出異常。如圖:
到此為止,我們已經能發現@Autowire注解注入屬性的原理:先根據類型注入,如果獲取到多個Bean,則根據名稱匹配,若名稱未匹配上就拋出異常。
總結
到此這篇關于Spring中@Autowire注入的文章就介紹到這了,更多相關Spring中@Autowire注入內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/qq_39600860/article/details/108678305