Spring Bean loading and Spring Bean Loading
Spring bean loading principle: After bean creation is complete, the ObjectFactory of bean creation will be exposed early and added to the cache.The singletonFatories bean is created only once in the Spring container. It will be obtained from the cache and loaded in the future. If it fails, it will be loaded in singletonFatories. IfCircular dependencyAccording to Spring's bean loading principle, the next bean needs to directly use ObjectFactory when dependent on the previous bean. The cache stores the original state of the bean, and bean instantiation is required. When Spring initializes bean, it first initializes the dependencies corresponding to this bean.
Package org. springframework. beans. factory;/*** Interface to be implemented by objects used within a {@ link BeanFactory} * which are themselves factories. if a bean implements this interface, * it is used as a factory for an object to expose, not directly as a bean * instance that will be exposed itself. */public interface FactoryBean <T> {/*** Return an instance (possibly shared or independent) of Object * managed by this factory. */T getObject () throws Exception;/*** Return the type of object that this FactoryBean creates, * or {@ code null} if not known in advance. */Class <?> GetObjectType ();/*** Is the object managed by this factory a singleton? That is, * will {@ link # getObject ()} always return the same object * (a reference that can be cached )? * The singleton object will be placed in the Spring Singleton cache pool */boolean isSingleton ();}
The factory Method Configuration bean is as follows:
<bean id="book" class="com.xxx.model.BookFactory"/>
BookFactory implements FactoryBean, then when getBean ("book") is used, the returned object of FactoryBean # getObject () method, that is, FactoryBean # getObject () represents the getBean () method:
Book book = ctx.getBean("book");
To obtain the BookFactoryBean object, use the prefix "&" as follows:
BookFactory bookFactory = ctx.getBean("&book");
Steps to obtain singleton:
SingletonObjects <BeanName, BeanInstance>. get (beanName ):Obtain the Map Singleton cache. Synchronized (this. singletonObjects), global variable synchronization. Required bytes required bytes = Null then bytes
EarlySingletonObjects <BeanName, BeanInstance>. get (beanName ):Process cyclic reference dependency detection. Required bytes required bytes = Null then bytes
SingletonFactories <BeanName, BeanFactory>. get (beanName ):Call
Create a factory for the corresponding SingletonGetObject () returns the Bean object. Response metadata --> earlySingletonObjects. put (beanName, singletonObject) stores the obtained Bean instance. --> SingletonFactories. remove (beanName) remove the singletonFactories factory corresponding to beanName.
Bean creation:
Bean initialization:Aware method, Post processing, and Init processing.