One: Introduction to cyclic dependencies

Take a look at the spring website for a description of loop dependencies in the Spring IOC container

One: Spring’s level 3 cache

  • Level 1 cache (also known as single-interest pool) singletonObjects: hold Bean objects that have recently gone through a full cycle
  • Level 2 cache earlySingletonObjects: Stores Bean objects that have been exposed early in their life cycle
  • SingletonFactories: A factory that stores beans that can be generated

Only simple beans are exposed ahead of time through level 3 caching to solve the problem of loop dependency. Non-simple bean, on the other hand, is recreated every time a new object is retrieved from the container, so there is no cache for non-simple bean.

The basic idea of using three-level cache to solve cycle dependence is as follows:

Three: source code analysis

Initialization of the container: this finishBeanFactoryInitialization (the beanFactory);

  • Access to the Singleton

Fetch cache from level 1 cache

  • CreateBean does not get sharedInstance== NULL from cache for the first time, so start creating Bean

The doCreateBean gets to work

The cache is being utilized! Level 1 cache does not exist, it was first created by singletonFactory and then deleted from level 2 cache. At this time, there is nothing in level 2 cache, so it is an empty delete

  • Fill property: populateBean

To be continued…

Four: why not use three-level cache instead of two-level cache?

Basic steps:

  1. After the creation A object is initialized, A post-processor is executed to create dynamic proxy A, and Factory(A) is created in the Factory pool, which is preprocessed only if A is referenced
  2. Reference A when filling B with properties, put dynamic proxy A into the semi-finished product, and then fill B with semi-finished product A
  3. And then B does the post-processing
  4. A Factory(B) is added to the Factory pool after the dynamic proxy B is put into the simple interest pool
  5. When A applies B, you just take B in the simple interest pool
  6. When A is initialized again, the dynamic proxy will be executed, but at this time there is already dynamic proxy A in the half-product pool, so there is no need to call dynamic proxy to create A, just move A from the semi-product pool to the simple profit pool, and finally delete Factory (A) from the Factory pool.