<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          終于有人把 Spring 循環(huán)依賴講清楚了!

          共 4915字,需瀏覽 10分鐘

           ·

          2020-10-14 06:05

          Java技術(shù)棧

          www.javastack.cn

          關(guān)注閱讀更多優(yōu)質(zhì)文章



          來源:CodeBear的園子
          地址:www.cnblogs.com/CodeBear/p/13327899.html

          網(wǎng)上關(guān)于Spring循環(huán)依賴的博客太多了,有很多都分析的很深入,寫的很用心,甚至還畫了時序圖、流程圖幫助讀者理解,我看了后,感覺自己是懂了,但是閉上眼睛,總覺得還沒有完全理解,總覺得還有一兩個坎過不去,對我這種有點笨的人來說,真的好難。

          當(dāng)時,我就在想,如果哪一天,我理解了Spring循環(huán)依賴,一定要用自己的方式寫篇博客,幫助大家更好的理解,等我理解后,一直在構(gòu)思,到底怎么應(yīng)該寫,才能更通俗易懂,就在前幾天,我想通了,這么寫應(yīng)該更通俗易懂。在寫本篇博客之前,我翻閱了好多關(guān)于Spring循環(huán)依賴的博客,網(wǎng)上應(yīng)該還沒有像我這樣講解的,現(xiàn)在就讓我們開始把。

          什么是循環(huán)依賴

          一言以蔽之:兩者相互依賴。

          在開發(fā)中,可能經(jīng)常出現(xiàn)這種情況,只是我們平時并沒有注意到原來我們寫的兩個類、甚至多個類相互依賴了,為什么注意不到呢?

          當(dāng)然是因為沒有報錯,而且一點問題都木有,如果報錯了,或者產(chǎn)生了問題,我們還會注意不到嗎?

          這一切都是Spring的功勞,它在后面默默的為我們解決了循環(huán)依賴的問題。大家可以關(guān)注公眾號Java技術(shù)棧回復(fù)spring閱讀系列Spring教程。

          如下所示:

          @Configuration
          @ComponentScan
          public?class?AppConfig?{
          }
          @Service
          public?class?AuthorService?{
          ????@Autowired
          ????BookService?bookService;
          }
          @Service
          public?class?BookService?{
          ????@Autowired
          ????AuthorService?authorService;
          }
          public?class?Main?{
          ????public?static?void?main(String[]?args)?{
          ????????ApplicationContext?annotationConfigApplicationContext?=?new?AnnotationConfigApplicationContext(AppConfig.class);

          ????????BookService?bookService?=?(BookService)?annotationConfigApplicationContext.getBean("bookService");
          ????????System.out.println(bookService.authorService);

          ????????AuthorService?authorService?=?(AuthorService)?annotationConfigApplicationContext.getBean("authorService");
          ????????System.out.println(authorService.bookService);
          ????}
          }

          運行結(jié)果:

          com.codebear.springcycle.AuthorService@63376bed
          com.codebear.springcycle.BookService@4145bad8

          可以看到BookService中需要AuthorService,AuthorService中需要BookService,類似于這樣的就叫循環(huán)依賴,但是神奇的是竟然一點問題沒有。

          當(dāng)然有些小伙伴可能get不到它的神奇之處,至于它的神奇之處在哪里,我們放到后面再說。

          任何循環(huán)依賴,Spring都能解決嗎

          不行。

          如果是原型 bean的循環(huán)依賴,Spring無法解決:

          @Service
          @Scope(BeanDefinition.SCOPE_PROTOTYPE)
          public?class?BookService?{????
          ????@Autowired
          ????AuthorService?authorService;
          }
          @Service
          @Scope(BeanDefinition.SCOPE_PROTOTYPE)
          public?class?AuthorService?{????
          ????@Autowired
          ????BookService?bookService;
          }

          啟動后,令人恐懼的紅色字體在控制臺出現(xiàn)了:

          如果是構(gòu)造參數(shù)注入的循環(huán)依賴,Spring無法解決:

          @Service
          public?class?AuthorService?{
          ????BookService?bookService;

          ????public?AuthorService(BookService?bookService)?{
          ????????this.bookService?=?bookService;
          ????}
          }
          @Service
          public?class?BookService?{

          ????AuthorService?authorService;

          ????public?BookService(AuthorService?authorService)?{
          ????????this.authorService?=?authorService;
          ????}
          }

          還是討厭的紅色字體:

          循環(huán)依賴可以關(guān)閉嗎

          可以,Spring提供了這個功能,我們需要這么寫:

          public?class?Main?{
          ????public?static?void?main(String[]?args)?{
          ????????AnnotationConfigApplicationContext?applicationContext?=?new?AnnotationConfigApplicationContext();
          ????????applicationContext.setAllowCircularReferences(false);
          ????????applicationContext.register(AppConfig.class);
          ????????applicationContext.refresh();
          ????}
          }

          再次運行,就報錯了:

          需要注意的是,我們不能這么寫:

          AnnotationConfigApplicationContext?applicationContext?=?new?AnnotationConfigApplicationContext(AppConfig.class);
          applicationContext.setAllowCircularReferences(false);

          如果你這么寫,程序執(zhí)行完第一行代碼,整個Spring容器已經(jīng)初始化完成了,你再設(shè)置不允許循環(huán)依賴,也于事無補了。bean 實例化原理,推薦看下。關(guān)注公眾號Java技術(shù)棧回復(fù)spring閱讀系列Spring教程。

          可以循環(huán)依賴的神奇之處在哪

          有很多小伙伴可能并不覺得可以循環(huán)依賴有多么神奇,那是因為不知道矛盾點在哪,接下來就來說說這個問題:
          當(dāng)beanA,beanB循環(huán)依賴:

          1. 創(chuàng)建beanA,發(fā)現(xiàn)依賴beanB;

          2. 創(chuàng)建beanB,發(fā)現(xiàn)依賴beanA;

          3. 創(chuàng)建beanA,發(fā)現(xiàn)依賴beanB;

          4. 創(chuàng)建beanB,發(fā)現(xiàn)依賴beanA。

          ...

          好了,死循環(huán)了。

          循環(huán)依賴的矛盾點就在于要創(chuàng)建beanA,它需要beanB,而創(chuàng)建beanB,又需要beanA,然后兩個bean都創(chuàng)建不出來。

          如何簡單的解決循環(huán)依賴

          如果你曾經(jīng)看過Spring循環(huán)依賴依賴的博客(比如這篇:圖解Spring循環(huán)依賴),應(yīng)該知道它其中有好幾個Map,一個Map放的是最完整的對象,稱為singletonObjects,一個Map放的是提前暴露出來的對象,稱為earlySingletonObjects。

          在這里,先要解釋下這兩個東西:

          • singletonObjects:單例池,其中存放的是經(jīng)歷了Spring完整生命周期的bean,這里面的bean的依賴都已經(jīng)填充完畢了。

          • earlySingletonObjects:提前暴露出來的對象的map,其中存放的是剛剛創(chuàng)建出來的對象,沒有經(jīng)歷Spring完整生命周期的bean,這里面的bean的依賴還未填充完畢。

          我們可以這么做:

          1. 當(dāng)我們創(chuàng)建完beanA,就把自己放到earlySingletonObjects,發(fā)現(xiàn)自己需要beanB,然后就去屁顛屁顛創(chuàng)建beanB;

          2. 當(dāng)我們創(chuàng)建完beanB,就把自己放到earlySingletonObjects,發(fā)現(xiàn)自己需要beanA,然后就去屁顛屁顛創(chuàng)建beanA;

          3. 創(chuàng)建beanA前,先去earlySingletonObjects看一下,發(fā)現(xiàn)自己已經(jīng)被創(chuàng)建出來了,把自己返回出去;

          4. beanB拿到了beanA,beanB創(chuàng)建完畢,把自己放入singletonObjects;

          5. beanA可以去singletonObjects拿到beanB了,beanA也創(chuàng)建完畢,把自己放到singletonObjects。
            整個過程結(jié)束。

          下面讓我們來實現(xiàn)這個功能:
          首先,自定義一個注解,字段上打上這個注解的,說明需要被Autowired:

          @Retention(RetentionPolicy.RUNTIME)
          public?@interface?CodeBearAutowired?{
          }

          再創(chuàng)建兩個循環(huán)依賴的類:

          public?class?OrderService?{
          ????@CodeBearAutowired
          ????public?UserService?userService;
          }
          public?class?UserService?{
          ????@CodeBearAutowired
          ????public?OrderService?orderService;
          }

          然后就是核心,創(chuàng)建對象,填充屬性,并解決Spring循環(huán)依賴的問題:

          public?class?Cycle?{
          ????//?單例池,里面放的是完整的bean,已完成填充屬性
          ????private?final?Map?singletonObjects?=?new?ConcurrentHashMap<>();

          ????//?存放的是提前暴露出來的bean,沒有經(jīng)歷過spring完整的生命周期,沒有填充屬性
          ????private?final?Map?earlySingletonObjects?=?new?HashMap<>();

          ????//?在Spring中,這個map存放的是beanNam和beanDefinition的映射關(guān)系
          ????static?Map>?map?=?new?HashMap<>();
          ????static?{
          ????????map.put("orderService",?OrderService.class);
          ????????map.put("userService",?UserService.class);
          ????}
          ????//?如果先調(diào)用init方法,就是預(yù)加載,如果直接調(diào)用getBean就是懶加載,兩者的循環(huán)依賴問題都解決了
          ????public?void?init()?{
          ????????for?(Map.Entry>?stringClassEntry?:?map.entrySet())?{
          ????????????createBean(stringClassEntry.getKey());
          ????????}
          ????}

          ????public?Object?getBean(String?beanName)?{
          ????????//?嘗試從singletonObjects中取,
          ????????Object?singletonObject?=?this.singletonObjects.get(beanName);
          ????????if?(singletonObject?!=?null)?{
          ????????????return?singletonObject;
          ????????}

          ????????//?嘗試從earlySingletonObjects取
          ????????singletonObject?=?this.earlySingletonObjects.get(beanName);
          ????????if?(singletonObject?!=?null)?{
          ????????????return?singletonObject;
          ????????}

          ????????return?createBean(beanName);
          ????}

          ????private?Object?createBean(String?beanName)?{
          ????????Object?singletonObject;

          ????????try?{
          ????????????//?創(chuàng)建對象
          ????????????singletonObject?=?map.get(beanName).getConstructor().newInstance();

          ????????????//?把沒有完成填充屬性的半成品?bean?放入earlySingletonObjects
          ????????????earlySingletonObjects.put(beanName,?singletonObject);

          ????????????//?填充屬性
          ????????????populateBean(singletonObject);

          ????????????//?bean創(chuàng)建成功,放入singletonObjects
          ????????????this.singletonObjects.put(beanName,?singletonObject);

          ????????????return?singletonObject;
          ????????}?catch?(Exception?ignore)?{
          ????????}
          ????????return?null;
          ????}

          ????private?void?populateBean(Object?object)?{
          ????????Field[]?fields?=?object.getClass().getDeclaredFields();
          ????????for?(Field?field?:?fields)?{
          ????????????if?(field.getAnnotation(CodeBearAutowired.class)?!=?null)?{
          ????????????????Object?value?=?getBean(field.getName());
          ????????????????try?{
          ????????????????????field.setAccessible(true);
          ????????????????????field.set(object,?value);
          ????????????????}?catch?(IllegalAccessException?ignored)?{
          ????????????????}
          ????????????}
          ????????}
          ????}
          }

          預(yù)加載調(diào)用:

          public?class?Main?{
          ????public?static?void?main(String[]?args)?{
          ????????Cycle?cycle?=?new?Cycle();
          ????????cycle.init();
          ????????UserService?userService?=?(UserService)?cycle.getBean("userService");
          ????????OrderService?orderService?=?(OrderService)?cycle.getBean("orderService");
          ????????System.out.println(userService.orderService);
          ????????System.out.println(orderService.userService);
          ????}
          }

          運行結(jié)果:

          com.codebear.cycleeasy.OrderService@61baa894
          com.codebear.cycleeasy.UserService@b065c63

          懶加載調(diào)用:

          public?class?Main?{
          ????public?static?void?main(String[]?args)?{
          ????????Cycle?cycle?=?new?Cycle();
          ????????UserService?userService?=?(UserService)?cycle.getBean("userService");
          ????????OrderService?orderService?=?(OrderService)?cycle.getBean("orderService");
          ????????System.out.println(userService.orderService);
          ????????System.out.println(orderService.userService);
          ????}
          }

          運行結(jié)果:

          com.codebear.cycleeasy.OrderService@61baa894
          com.codebear.cycleeasy.UserService@b065c63

          為什么無法解決原型、構(gòu)造方法注入的循環(huán)依賴

          在上面,我們自己手寫了解決循環(huán)依賴的代碼,可以看到,核心是利用一個map,來解決這個問題的,這個map就相當(dāng)于緩存。

          為什么可以這么做,因為我們的bean是單例的,而且是字段注入(setter注入)的,單例意味著只需要創(chuàng)建一次對象,后面就可以從緩存中取出來,字段注入,意味著我們無需調(diào)用構(gòu)造方法進行注入。

          • 如果是原型bean,那么就意味著每次都要去創(chuàng)建對象,無法利用緩存;

          • 如果是構(gòu)造方法注入,那么就意味著需要調(diào)用構(gòu)造方法注入,也無法利用緩存。

          需要aop怎么辦?

          我們上面的方案看起來很美好,但是還有一個問題,如果我們的bean創(chuàng)建出來,還要做一點加工,怎么辦?也許,你沒有理解這句話的意思,再說的明白點,如果beanA和【beanB的代理對象】循環(huán)依賴,或者【beanA的代理對象】和beanB循環(huán)依賴,再或者【beanA的代理對象】和【beanB的代理對象】循環(huán)依賴,怎么辦?

          這里說的創(chuàng)建代理對象僅僅是“加工”的其中一種可能。

          遇到這種情況,我們總不能把創(chuàng)建完的對象直接扔到緩存把?我們這么做的話,如果【beanA的代理對象】和【beanB的代理對象】循環(huán)依賴,我們最終獲取的beanA中的beanB還是beanB,并非是beanB的代理對象。

          聰明的你,一定在想,這還不簡單嗎:
          我們創(chuàng)建完對象后,判斷這個對象是否需要代理,如果需要代理,創(chuàng)建代理對象,然后把代理對象放到earlySingletonObjects不就OJ8K了?
          就像這樣:

          private?Object?createBean(String?beanName)?{
          ????Object?singletonObject;

          ????try?{
          ????????//?創(chuàng)建對象
          ????????singletonObject?=?map.get(beanName).getConstructor().newInstance();

          ????????//?創(chuàng)建bean的代理對象
          ????????/**
          ?????????*?if(?需要代理){
          ?????????*?????singletonObject=創(chuàng)建代理對象;
          ?????????*
          ?????????*?}
          ?????????*/

          ????????//?把沒有完成填充屬性的半成品?bean?放入earlySingletonObjects
          ????????earlySingletonObjects.put(beanName,?singletonObject);

          ????????//?填充屬性
          ????????populateBean(singletonObject);

          ????????//?bean創(chuàng)建成功,放入singletonObjects
          ????????this.singletonObjects.put(beanName,?singletonObject);

          ????????return?singletonObject;
          ????}?catch?(Exception?ignore)?{
          ????
          ????}
          ????return?null;
          }

          這確實可以,但是,這違反了Spring的初衷,Spring的初衷是希望在bean生命周期的最后幾步才去aop,如果像上面說的這么做,就意味著一旦創(chuàng)建完對象,Spring就會去aop了,這就違反了Spring的初衷,所以Spring并沒有這么做。

          但是如果真的出現(xiàn)了aop bean循環(huán)依賴,就沒辦法了,只能先去aop,但是如果沒有出現(xiàn)循環(huán)依賴,Spring并不希望在這里就進行aop,所以Spring引入了Map>,ObjectFactory是一個函數(shù)式接口,可以理解為工廠方法,當(dāng)創(chuàng)建完對象后,把【獲得這個對象的工廠方法】放入這個map,等真的發(fā)生循環(huán)依賴,就去執(zhí)行這個【獲得這個對象的工廠方法】,獲取加工完成的對象。

          下面直接放出代碼:

          public?class?Cycle?{
          ????//?單例池,里面放的是完整的bean,已完成填充屬性
          ????private?final?Map?singletonObjects?=?new?ConcurrentHashMap<>();

          ????//?存放的是?加工bean的工廠方法
          ????private?final?Map>?singletonFactories?=?new?HashMap<>();

          ????//?存放的是提前暴露出來的bean,沒有經(jīng)歷過spring完整的生命周期,沒有填充屬性
          ????private?final?Map?earlySingletonObjects?=?new?HashMap<>();

          ????private?final?Set?singletonsCurrentlyInCreation?=?new?HashSet<>();

          ????static?Map>?map?=?new?HashMap<>();

          ????static?{
          ????????map.put("orderService",?OrderService.class);
          ????????map.put("userService",?UserService.class);
          ????}

          ????public?void?init()?{
          ????????for?(Map.Entry>?stringClassEntry?:?map.entrySet())?{
          ????????????createBean(stringClassEntry.getKey());
          ????????}
          ????}

          ????private?Object?createBean(String?beanName)?{
          ????????Object?instance?=?null;
          ????????try?{
          ????????????instance?=?map.get(beanName).getConstructor().newInstance();
          ????????}?catch?(Exception?ex)?{
          ????????}


          ????????Object?finalInstance?=?instance;
          ????????this.singletonFactories.put(beanName,?()?->?{
          ????????????//?創(chuàng)建代理對象
          ????????????return?finalInstance;
          ????????});

          ????????populateBean(instance);

          ????????this.singletonObjects.put(beanName,?instance);
          ????????return?instance;
          ????}

          ????public?Object?getBean(String?beanName)?{
          ????????//?嘗試從singletonObjects中取,
          ????????Object?singletonObject?=?this.singletonObjects.get(beanName);
          ????????if?(singletonObject?!=?null)?{
          ????????????return?singletonObject;
          ????????}

          ????????//?嘗試從earlySingletonObjects取
          ????????singletonObject?=?this.earlySingletonObjects.get(beanName);
          ????????if?(singletonObject?!=?null)?{
          ????????????return?singletonObject;
          ????????}

          ????????//?嘗試從singletonFactories取出工廠方法
          ????????ObjectFactory?objectFactory?=?this.singletonFactories.get(beanName);
          ????????if?(objectFactory?!=?null)?{
          ????????????singletonObject?=?objectFactory.getObject();
          ????????????this.earlySingletonObjects.put(beanName,?singletonObject);
          ????????????return?singletonObject;
          ????????}

          ????????return?createBean(beanName);
          ????}

          ????private?void?populateBean(Object?object)?{
          ????????Field[]?fields?=?object.getClass().getDeclaredFields();
          ????????for?(Field?field?:?fields)?{
          ????????????if?(field.getAnnotation(CodeBearAutowired.class)?!=?null)?{
          ????????????????Object?value?=?getBean(field.getName());
          ????????????????try?{
          ????????????????????field.setAccessible(true);
          ????????????????????field.set(object,?value);
          ????????????????}?catch?(IllegalAccessException?ignored)?{
          ????????????????}
          ????????????}
          ????????}
          ????}
          }

          調(diào)用方法:

          ?public?static?void?main(String[]?args)?{
          ????Cycle?cycle?=?new?Cycle();
          ????cycle.init();
          ????System.out.println(((UserService)?cycle.getBean("userService")).orderService);
          ????System.out.println(((OrderService)?cycle.getBean("orderService")).userService);
          }

          運行結(jié)果:

          com.codebear.cycles.OrderService@49e4cb85
          com.codebear.cycles.UserService@2133c8f8

          二級緩存能不能解決循環(huán)依賴,三級循環(huán)到底有什么用?

          我的觀點可能和網(wǎng)上的主流觀點有很大的出入,至于我的觀點是對是錯,請各位自行判斷。

          二級緩存可以解決循環(huán)依賴,哪怕aop bean循環(huán)依賴,上面我們已經(jīng)提到了,我們可以創(chuàng)建完對象,直接創(chuàng)建代理對象,把代理對象放入二級緩存,這樣我們從二級緩存獲得的一定是aop bean,并非是bean本身。

          三級緩存有什么用?網(wǎng)上的主流觀點是為了解決循環(huán)依賴,還有就是為了效率,為了解決循環(huán)依賴,我們上面已經(jīng)討論過了,我的觀點是二級緩存已經(jīng)可以解決循環(huán)依賴了,下面就讓我們想想,和效率是否有關(guān)系?

          我的觀點是沒有關(guān)系,理由如下:
          我們把【獲得對象的工廠方法】放入了map

          • 如果沒有循環(huán)依賴,這個map根本沒有用到,和效率沒有關(guān)系;

          • 如果是普通bean循環(huán)依賴,三級緩存直接返回了bean,和效率還是沒有關(guān)系;

          • 如果是aop bean循環(huán)依賴,如果沒有三級緩存,直接創(chuàng)建代理對象,放入二級緩存,如果有三級緩存,還是需要創(chuàng)建代理對象,只是兩者的時機不同,和效率還是沒有關(guān)系。

          有了這篇博客的基礎(chǔ),當(dāng)你再看其他關(guān)于Spring循環(huán)依賴的博客,應(yīng)該會輕松的多,因為我們畢竟自己解決了循環(huán)依賴,Spring的循環(huán)依賴只是在我們之上做了進一步的封裝與改進。





          關(guān)注Java技術(shù)棧看更多干貨



          戳原文,獲取精選面試題!
          瀏覽 41
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日韩无码色| 91欧美性爱 | 99色图 | 9l视频自拍九色9l视频成人 | 成年人毛片国产网站国产片 |