看了這節,還是沒明白里面的內部邏輯,泛型的注解是怎么用的,有人能講解下么,還有s1哪個報錯,修改為Store后返回的不還是StringStore么?這有什么區別?
@Autowired private?Store<String>?s1; @Autowired private?Store<Integer>?s2; @Bean?????? public?StringStore?stringStore()?{ ????return?new?StringStore();?? } @Bean?????? public?IntegerStore?integerStore()?{ ????return?new?IntegerStore();?? } @Bean(name?=?"stringStoreTest") public?Store?stringStoreTest()?{ ??System.out.println("s1?:?"?+?s1.getClass().getName());?? ??System.out.println("s2?:?"?+?s2.getClass().getName()); ??return?new?StringStore(); }
測試類:
@Test public?void?testG()?{ ????StringStore?store?=?super.getBean("stringStoreTest"); }
有點困惑,不知道這段講了什么,有人能講解下么?
尤其是主函數部分的三個@Bean,還有@Autowired,我還是不太明白里面的邏輯
還有S1哪個報錯,修改為Store后返回的不還是StringStore么?那么在@Autowired的時候,它是怎么區分的??
或者說查找的時候是看聲明的返回值的類型?那么如果還有一個類實現了Store<String>的,也正好@Bean了,是不是也是無法區分
@Bean public?StringStore?stringStore(){ ????return?new?StringStore();?? }
@Bean(name="stringStoreTest") public?Store?stringStoreTest(){ ????return?new?StringStore(); }
2017-09-18
首先interface? store<T>,泛型接口,
接下來2個實現類,StringStore和IntegerStore
////////////////////////////
@Bean
public?StringStore?stringStore(){??
?return?new?StringStore();?
}
這里沒有指定bean的name,默認是成員方法的名字,即stringStore。spring掃描之后初始化的名為stringStore的bean注冊到容器中,此時容器中有一個名為stringStore的bean。
/////////////////////////////
@Bean????
?public?IntegerStore?integerStore()?{??
?return?new?IntegerStore();?
}解釋同上此時,此時容器中有2個bean,分別為stringStore和integerStore.
//////////////////////
@Autowired
private?Store<String>?s1;
@Autowired
private?Store<Integer>?s2;
@Autowired注解是按照類型在容器中搜索相應的bean,s1對應容器中的stringStore,s2對應integerStore。///////////////////////////
@Bean(name?=?"stringStoreTest")
public?Store?stringStoreTest()?{?
System.out.println("s1?:?"?+?s1.getClass().getName());???
System.out.println("s2?:?"?+?s2.getClass().getName());?
return?new?StringStore();}
此時這個方法里面用到的s1,s2就對應不是空了。@bean注解會被掃描初始化生成一個指定名字為stringStoreTest的bean注冊到容器中。返回類型是Store時,通過3個@Bean初始化的bean注冊到容器中的類型不同,而@Auto wired注解也不會通過類型匹配錯誤,從而導致s1空指針。當返回類型是StringStore時,容器中會出現2個類型是String Store的bean,@Autowired從容器中通過類型匹配時會出錯,不知道是哪一個即bean不唯一,無法匹配,s1為空,即報空指針錯誤。
解決辦法可以用老師的方法修改返回類型,也可以用@Qualifier指定名字,或者使用@Resource注解。
2017-04-10
我這里試的時候,報錯會說Store<String>不唯一,然后junit會報null pointer Exception,即使像老師說的那樣改了,依舊是一樣的結果。。。。
2017-02-11
@Bean 注解的方法,在注冊bean對象的時候,就是根據方法返回值類型確定其類型的。
“如果還有一個類實現了Store<String>的,也正好@Bean了,是不是也是無法區分” ,當然了
2016-12-18
我也沒看懂這節課的邏輯,他為什么要講這節課啊
2016-12-14
這里主要是講解了注解方式的依賴注入和泛型注入;
@Bean 實際上就是 在xml中定義一個bean 就相當于<bean id="xx" class="com.xx.xxx"></bean>
@Autowired 注解就是注入值 ?在屬性上邊使用該注解 ?就相當于?
<bean id="xx" class="com.xx.xx">
????<property name="xxx" ref="xxx" />
</bean>