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

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

到此為止,我們已經(jīng)能發(fā)現(xiàn)@Autowire注解注入屬性的原理:先根據(jù)類型注入,如果獲取到多個Bean,則根據(jù)名稱匹配,若名稱未匹配上就拋出異常。
總結(jié)
到此這篇關(guān)于Spring中@Autowire注入的文章就介紹到這了,更多相關(guān)Spring中@Autowire注入內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java數(shù)據(jù)類型轉(zhuǎn)換實例解析
這篇文章主要介紹了Java數(shù)據(jù)類型轉(zhuǎn)換實例解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-11-11
SpringSecurity登錄使用JSON格式數(shù)據(jù)的方法
這篇文章主要介紹了SpringSecurity登錄使用JSON格式數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-02-02
IntelliJ IDEA失焦自動重啟服務(wù)的解決方法
在使用 IntelliJ IDEA運行 SpringBoot 項目時,你可能會遇到一個令人困擾的問題,一旦你的鼠標(biāo)指針離開當(dāng)前IDE窗口,點擊其他位置時, IDE 窗口會失去焦點,你的 SpringBoot 服務(wù)就會自動重啟,所以本文給大家介紹了IntelliJ IDEA失焦自動重啟服務(wù)的解決方法2023-10-10

