一文讀懂Spring 循環(huán)依賴,寫得太好了!(建議收藏)
點擊上方[全棧開發(fā)者社區(qū)]→右上角[...]→[設(shè)為星標?]

轉(zhuǎn)自:Vt
鏈接:juejin.im/post/5e927e27f265da47c8012ed9
前言
正文


if?(isPrototypeCurrentlyInCreation(beanName))?{
??throw?new?BeanCurrentlyInCreationException(beanName);
}

Spring解決循環(huán)依賴
singletonObjects 它是我們最熟悉的朋友,俗稱“單例池”“容器”,緩存創(chuàng)建完成單例Bean的地方。 singletonFactories 映射創(chuàng)建Bean的原始工廠 earlySingletonObjects 映射Bean的早期引用,也就是說在這個Map里的Bean不是完整的,甚至還不能稱之為“Bean”,只是一個Instance.

循環(huán)依賴的本質(zhì)
將指定的一些類實例為單例 類中的字段也都實例為單例 支持循環(huán)依賴
public?class?A?{
????private?B?b;
}
//?類B:
public?class?B?{
????private?A?a;
}
?/**
?????*?放置創(chuàng)建好的bean?Map
?????*/
????private?static?Map?cacheMap?=?new?HashMap<>(2);
????public?static?void?main(String[]?args)?{
????????//?假裝掃描出來的對象
????????Class[]?classes?=?{A.class,?B.class};
????????//?假裝項目初始化實例化所有bean
????????for?(Class?aClass?:?classes)?{
????????????getBean(aClass);
????????}
????????//?check
????????System.out.println(getBean(B.class).getA()?==?getBean(A.class));
????????System.out.println(getBean(A.class).getB()?==?getBean(B.class));
????}
????@SneakyThrows
????private?static??T?getBean(Class?beanClass) ?{
????????//?本文用類名小寫?簡單代替bean的命名規(guī)則
????????String?beanName?=?beanClass.getSimpleName().toLowerCase();
????????//?如果已經(jīng)是一個bean,則直接返回
????????if?(cacheMap.containsKey(beanName))?{
????????????return?(T)?cacheMap.get(beanName);
????????}
????????//?將對象本身實例化
????????Object?object?=?beanClass.getDeclaredConstructor().newInstance();
????????//?放入緩存
????????cacheMap.put(beanName,?object);
????????//?把所有字段當(dāng)成需要注入的bean,創(chuàng)建并注入到當(dāng)前bean中
????????Field[]?fields?=?object.getClass().getDeclaredFields();
????????for?(Field?field?:?fields)?{
????????????field.setAccessible(true);
????????????//?獲取需要注入字段的class
????????????Class>?fieldClass?=?field.getType();
????????????String?fieldBeanName?=?fieldClass.getSimpleName().toLowerCase();
????????????//?如果需要注入的bean,已經(jīng)在緩存Map中,那么把緩存Map中的值注入到該field即可
????????????//?如果緩存沒有?繼續(xù)創(chuàng)建
????????????field.set(object,?cacheMap.containsKey(fieldBeanName)
??????????????????????cacheMap.get(fieldBeanName)?:?getBean(fieldClass));
????????}
????????//?屬性填充完成,返回
????????return?(T)?object;
????}

what?問題的本質(zhì)居然是two sum!
class?Solution?{
????public?int[]?twoSum(int[]?nums,?int?target)?{
????????Map?map?=?new?HashMap<>();
????????for?(int?i?=?0;?i?????????????int?complement?=?target?-?nums[i];
????????????if?(map.containsKey(complement))?{
????????????????return?new?int[]?{?map.get(complement),?i?};
????????????}
????????????map.put(nums[i],?i);
????????}
????????throw?new?IllegalArgumentException("No?two?sum?solution");
????}
}
結(jié)尾
覺得本文對你有幫助?請分享給更多人
關(guān)注「全棧開發(fā)者社區(qū)」加星標,提升全棧技能
本公眾號會不定期給大家發(fā)福利,包括送書、學(xué)習(xí)資源等,敬請期待吧!
如果感覺推送內(nèi)容不錯,不妨右下角點個在看轉(zhuǎn)發(fā)朋友圈或收藏,感謝支持。
好文章,留言、點贊、在看和分享一條龍吧??
評論
圖片
表情
