How to use the third-level cache in Spring?

The three-level cache in the Spring framework is used to cache the creation of Beans, mainly to solve the problem of circular dependencies. This cache includes three levels: singletonFactories, earlySingletonObjects, and singletonObjects.

  1. Singleton factories cache: stores factory objects of beans that have been created but not yet initialized. When a bean is needed, it first looks in this cache. If the corresponding factory object is found, it is used to create and return the bean.
  2. earlySingletonObjects cache: stores Bean objects that have been initialized but have not yet completed all lifecycle methods. When a Bean’s initialization method is currently being executed, the Bean is placed in the earlySingletonObjects cache. Other Beans that depend on this Bean will retrieve the already initialized Bean object from this cache.
  3. singletonObjects cache: stores Bean objects that have been initialized and have completed all lifecycle methods. After the initialization method of a Bean is completed, it is removed from the earlySingletonObjects cache and placed into the singletonObjects cache.

The specific steps of using three-level caching are as follows:

  1. Firstly, check if the caching object of the bean already exists by using the getSingleton method of the DefaultSingletonBeanRegistry class. If it does, retrieve the bean object directly from the singletonObjects cache; otherwise, proceed to the next step.
  2. Next, call the createBean method to create a Bean object. During the process of creating the Bean object, it will first look for the existence of the Bean’s factory object in the singletonFactories cache. If it exists, it will use that factory object for creation and place the created Bean object in the earlySingletonObjects cache.
  3. Then, proceed to execute the createBean method, completing the initialization of the Bean object and executing lifecycle methods. During this process, if there are other Beans that depend on this Bean, they will be retrieved from the earlySingletonObjects cache where the Bean objects have already been initialized.
  4. Finally, the initialized Bean objects are placed in the singletonObjects cache and removed from the earlySingletonObjects cache.

By utilizing a three-level cache, the Spring framework can address the issue of circular dependencies and improve the efficiency of bean creation and initialization.

bannerAds