幫助你更好的理解Spring循環依賴

網上關於Spring循環依賴的博客太多了,有很多都分析的很深入,寫的很用心,甚至還畫了時序圖、流程圖幫助讀者理解,我看了後,感覺自己是懂了,但是閉上眼睛,總覺得還沒有完全理解,總覺得還有一兩個坎過不去,對我這種有點笨的人來說,真的好難。當時,我就在想,如果哪一天,我理解了Spring循環依賴,一定要用自己的方式寫篇博客,幫助大家更好的理解,等我理解後,一直在構思,到底怎麼應該寫,才能更通俗易懂,就在前幾天,我想通了,這麼寫應該更通俗易懂。在寫本篇博客之前,我翻閱了好多關於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);
    }
}

運行結果:

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

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

當然有些小夥伴可能get不到它的神奇之處,至於它的神奇之處在哪裏,我們放到後面再說。

任何循環依賴,Spring都能解決嗎

不行。

如果是原型 bean的循環依賴,Spring無法解決:

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

啓動後,令人恐懼的紅色字體在控制檯出現了:


如果是構造參數注入的循環依賴,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;
    }
}

還是討厭的紅色字體:


循環依賴可以關閉嗎

可以,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);

如果你這麼寫,程序執行完第一行代碼,整個Spring容器已經初始化完成了,你再設置不允許循環依賴,也於事無補了。

可以循環依賴的神奇之處在哪

有很多小夥伴可能並不覺得可以循環依賴有多麼神奇,那是因爲不知道矛盾點在哪,接下來就來說說這個問題:
當beanA,beanB循環依賴:

  1. 創建beanA,發現依賴beanB;
  2. 創建beanB,發現依賴beanA;
  3. 創建beanA,發現依賴beanB;
  4. 創建beanB,發現依賴beanA。
    ...
    好了,死循環了。

循環依賴的矛盾點就在於要創建beanA,它需要beanB,而創建beanB,又需要beanA,然後兩個bean都創建不出來。

如何簡單的解決循環依賴

如果你曾經看過Spring解決循環依賴的博客,應該知道它其中有好幾個Map,一個Map放的是最完整的對象,稱爲singletonObjects,一個Map放的是提前暴露出來的對象,稱爲earlySingletonObjects。

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

  • singletonObjects:單例池,其中存放的是經歷了Spring完整生命週期的bean,這裏面的bean的依賴都已經填充完畢了。
  • earlySingletonObjects:提前暴露出來的對象的map,其中存放的是剛剛創建出來的對象,沒有經歷Spring完整生命週期的bean,這裏面的bean的依賴還未填充完畢。

我們可以這麼做:

  1. 當我們創建完beanA,就把自己放到earlySingletonObjects,發現自己需要beanB,然後就去屁顛屁顛創建beanB;
  2. 當我們創建完beanB,就把自己放到earlySingletonObjects,發現自己需要beanA,然後就去屁顛屁顛創建beanA;
  3. 創建beanA前,先去earlySingletonObjects看一下,發現自己已經被創建出來了,把自己返回出去;
  4. beanB拿到了beanA,beanB創建完畢,把自己放入singletonObjects;
  5. beanA可以去singletonObjects拿到beanB了,beanA也創建完畢,把自己放到singletonObjects。
    整個過程結束。

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

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

再創建兩個循環依賴的類:

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

然後就是核心,創建對象,填充屬性,並解決Spring循環依賴的問題:

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

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

    // 在Spring中,這個map存放的是beanNam和beanDefinition的映射關係
    static Map<String, Class<?>> map = new HashMap<>();
    static {
        map.put("orderService", OrderService.class);
        map.put("userService", UserService.class);
    }
    // 如果先調用init方法,就是預加載,如果直接調用getBean就是懶加載,兩者的循環依賴問題都解決了
    public void init() {
        for (Map.Entry<String, Class<?>> 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 {
            // 創建對象
            singletonObject = map.get(beanName).getConstructor().newInstance();

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

            // 填充屬性
            populateBean(singletonObject);

            // bean創建成功,放入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) {
                }
            }
        }
    }
}

預加載調用:

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);
    }
}

運行結果:

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

懶加載調用:

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);
    }
}

運行結果:

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

爲什麼無法解決原型、構造方法注入的循環依賴

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

爲什麼可以這麼做,因爲我們的bean是單例的,而且是字段注入(setter注入)的,單例意味着只需要創建一次對象,後面就可以從緩存中取出來,字段注入,意味着我們無需調用構造方法進行注入。

  • 如果是原型bean,那麼就意味着每次都要去創建對象,無法利用緩存;
  • 如果是構造方法注入,那麼就意味着需要調用構造方法注入,也無法利用緩存。

需要aop怎麼辦?

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

這裏說的創建代理對象僅僅是“加工”的其中一種可能。

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

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

    private Object createBean(String beanName) {
        Object singletonObject;

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

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

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

            // 填充屬性
            populateBean(singletonObject);

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

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

這確實可以,但是,這違反了Spring的初衷,Spring的初衷是希望在bean生命週期的最後幾步纔去aop,如果像上面說的這麼做,就意味着一旦創建完對象,Spring就會去aop了,這就違反了Spring的初衷,所以Spring並沒有這麼做。

但是如果真的出現了aop bean循環依賴,就沒辦法了,只能先去aop,但是如果沒有出現循環依賴,Spring並不希望在這裏就進行aop,所以Spring引入了Map<String, ObjectFactory<?>>,ObjectFactory是一個函數式接口,可以理解爲工廠方法,當創建完對象後,把【獲得這個對象的工廠方法】放入這個map,等真的發生循環依賴,就去執行這個【獲得這個對象的工廠方法】,獲取加工完成的對象。

下面直接放出代碼:

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

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

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

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

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

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

    public void init() {
        for (Map.Entry<String, Class<?>> 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, () -> {
            // 創建代理對象
            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) {
                }
            }
        }
    }
}

調用方法:

 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);
    }

運行結果:

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

二級緩存能不能解決循環依賴,三級循環到底有什麼用?

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

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

三級緩存有什麼用?網上的主流觀點是爲了解決循環依賴,還有就是爲了效率,爲了解決循環依賴,我們上面已經討論過了,我的觀點是二級緩存已經可以解決循環依賴了,下面就讓我們想想,和效率是否有關係?

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

  • 如果沒有循環依賴,這個map根本沒有用到,和效率沒有關係;
  • 如果是普通bean循環依賴,三級緩存直接返回了bean,和效率還是沒有關係;
  • 如果是aop bean循環依賴,如果沒有三級緩存,直接創建代理對象,放入二級緩存,如果有三級緩存,還是需要創建代理對象,只是兩者的時機不同,和效率還是沒有關係。

有了這篇博客的基礎,當你再看其他關於Spring循環依賴的博客,應該會輕鬆的多,因爲我們畢竟自己解決了循環依賴,Spring的循環依賴只是在我們之上做了進一步的封裝與改進。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章