spring initialize Bean

Speaking of spring bean initialization naturally inseparable from the circular reference initialization phase;
a first spring container creates a beanFactory, new DefaultListableBeanFactory after startup.

2 refresh method and then start the process in spring container will call the core of the Chinese Communist Party in this method calls the nine method, is the initial process spring container, so that the spring container not only our narrow concept of the map so simple, in this method consists of two of the most major ways:

2.1 invokeBeanFactoryPostProcessors (beanFactory)
      In this method, calls beanFactory postprocessor spring will scan all the information gathered to be registered after javaClass Bean is to construct BeanDefinition, after register to beanDefinitionMap provided for future Bean initialization information.

2.2 finishBeanFactoryInitialization (beanFactory)
      which is even more extra important in the final stages of this method will call preInstantiateSingletons, it is clear that in this process we need to initialize the Scope for the single bean, and you do not need to do a prototype bean treated separately, because the prototype whether bean initialization phase or phases are injected directly create "objects or proxy objects"
     called getBean method preInstantiateSingletons method, after using the delegate model called doGetBean method. doGetBean method called twice getSingleton method, and after three cache Map (singleObjectMap, singletonFactory, earlySingleObjects) , the nature of the two calls is to solve the problem of circular references; because if circular references do not exist, they would direct method calls creatBean to go in the bean creation process.

      Then again, when the first call getSingleton directly specified circular reference is true, entered the second getSingleton method;
       (1) gets the start of the buffer pool to create a good bean bean object, but must obtain failure because the bean without completing the process of creating life cycle.
       (2) will go for the cache from earlySingletonObject Map, as has just created the first time that Bean has not been marked as "create state" still can not get it.
       (3) After two failed acquisition will be called the third getSingleton methods, lambda expressions method by createBean to go in the actual process of creating an object, and there is an important link before executing createBean is the current state of initial Bean It has been added to "create a state of the collection," and had to create the bean factory into a singletonFactoriesMap cache set.

 public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(beanName, "'beanName' must not be null");
        Map var3 = this.singletonObjects;
        synchronized(this.singletonObjects) {
            Object singletonObject = this.singletonObjects.get(beanName);
            if(singletonObject == null) {
                if(this.singletonsCurrentlyInDestruction) {
                    throw new BeanCreationNotAllowedException(beanName, "Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!)");
                }

                if(this.logger.isDebugEnabled()) {
                    this.logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
                }

                this.beforeSingletonCreation(beanName);
                boolean newSingleton = false;

 

protected void beforeSingletonCreation(String beanName) {
if(!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}

3 still continue to call doCreateBean method by entrusting mode in createBean method, doCreateBean method also has two core methods:

3.1 createInstance will create a java class itself wapper objects;

if(instanceWrapper == null) {
instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}

3.2 populateBean method will package object member variables are implanted with Bean annotated
      in this method will go to the assembly object autowire notes, this time will continue to call getBean method, and then call getSingleton method again, before the implementation of a series of repeated createBean operating.
      At this point it should be noted that the circular dependency occurs, the injection properties of the object will still hold the original target, but the original object when called a second time getSingleton method, they can already get to Factory through the secondary cache singleFactoryMap, and instantiate Bean put to earlySingleObjectMap three cache, so as to acquire the object. Such a circular dependency cycle will not cause an infinite loop is created. (Where plant secondary cache, may return to the original effect is enhanced proxy object or objects after AOP occur, in essence, the result is performed by post-processor Bean)

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if(bw == null) {
if(!((PropertyValues)pvs).isEmpty()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
} else {
boolean continueWithPropertyPopulation = true;
if(!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
Iterator var6 = this.getBeanPostProcessors().iterator();

while(var6.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var6.next();
if(bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
if(!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}

if(continueWithPropertyPopulation) {
if(mbd.getResolvedAutowireMode() == 1 || mbd.getResolvedAutowireMode() == 2) {
MutablePropertyValues newPvs = new MutablePropertyValues((PropertyValues)pvs);
if(mbd.getResolvedAutowireMode() == 1) {
this.autowireByName(beanName, mbd, bw, newPvs);
}

if(mbd.getResolvedAutowireMode() == 2) {
this.autowireByType(beanName, mbd, bw, newPvs);
}

pvs = newPvs;
}

boolean hasInstAwareBpps = this.hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = mbd.getDependencyCheck() != 0;
if(hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = this.filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if(hasInstAwareBpps) {
Iterator var9 = this.getBeanPostProcessors().iterator();

while(var9.hasNext()) {
BeanPostProcessor bp = (BeanPostProcessor)var9.next();
if(bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor)bp;
pvs = ibp.postProcessPropertyValues((PropertyValues)pvs, filteredPds, bw.getWrappedInstance(), beanName);
if(pvs == null) {
return;
}
}
}
}

if(needsDepCheck) {
this.checkDependencies(beanName, mbd, filteredPds, (PropertyValues)pvs);
}
}

this.applyPropertyValues(beanName, mbd, bw, (PropertyValues)pvs);
}
}
}
View Code

After the call attribute assembling 3.3 initializeBean method call interface to the callback function is implemented Bean, Bean is a series of post-processor method.

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
if(System.getSecurityManager() != null) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
AbstractAutowireCapableBeanFactory.this.invokeAwareMethods(beanName, bean);
return null;
}
}, this.getAccessControlContext());
} else {
this.invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if(mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
}

try {
this.invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable var6) {
throw new BeanCreationException(mbd != null?mbd.getResourceDescription():null, beanName, "Invocation of init method failed", var6);
}

if(mbd == null || !mbd.isSynthetic()) {
wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

return wrappedBean;
}
View Code

 

Guess you like

Origin www.cnblogs.com/zzq-include/p/11988310.html