圖解Spring解決循環(huán)依賴

來源:juejin.cn/post/6844904122160775176
前言
正文
if?(isPrototypeCurrentlyInCreation(beanName))?{??throw?new?BeanCurrentlyInCreationException(beanName);}
Spring解決循環(huán)依賴
循環(huán)依賴的本質(zhì)
將指定的一些類實(shí)例為單例
類中的字段也都實(shí)例為單例
支持循環(huán)依賴
public?class?A?{????private?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};????????//?假裝項(xiàng)目初始化實(shí)例化所有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));????}????????private?static??T?getBean(Class ?beanClass)?{ ????????//?本文用類名小寫?簡單代替bean的命名規(guī)則????????String?beanName?=?beanClass.getSimpleName().toLowerCase();????????//?如果已經(jīng)是一個(gè)bean,則直接返回????????if?(cacheMap.containsKey(beanName))?{????????????return?(T)?cacheMap.get(beanName);????????}????????//?將對象本身實(shí)例化????????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");????}}//作者:LeetCode//鏈接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2///來源:力扣(LeetCode)
結(jié)尾
評論
圖片
表情





