Blog index
Without further ado, let’s draw a conclusion. This article focuses on the sequential execution of the BeanPostProcessor class.
The specific instantiation process of beans is too complex. For those who are interested, please refer to Spring Source Code In Depth Analysis.
-
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
-
org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
-
org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
-
org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
-
org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference
-
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation
-
org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties
-
Org. Springframework. Beans. Factory. Config. InstantiationAwareBeanPostProcessor# postProcessPropertyValues executed before to null (7 8)
-
org.springframework.beans.factory.config.BeanPostProcessor#postProcessBeforeInitialization
InvokeInitMethods (Extension methods)
9.1 implements the afterPropertiesSet() method of the InitializingBean interface
9.2 Calling initMethod()
-
org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization
-
The extension method handles the implementation DisposableBean interface
The sample code removes the log and some non-analysis related
Because there are too many codes, only the key codes are selected. If you are interested, you can understand the process by following the article debug once.
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
Copy the code
And then into the org. Springframework. Beans. Factory. Support. AbstractBeanFactory# doGetBean
protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { String beanName = transformedBeanName(name); Object bean; // Eagerly check singleton cache for manually registered singletons. Object sharedInstance = getSingleton(beanName); if (sharedInstance ! = null && args == null) { bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else {// loop dependency, Throws an exception if (isPrototypeCurrentlyInCreation (beanName)) {throw new BeanCurrentlyInCreationException (beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); ... the if (! typeCheckOnly) { markBeanAsCreated(beanName); } try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); ··· · // Create bean instance. If (mbd.issingleton ()) {sharedInstance = getSingleton(beanName, Return createBean(beanName, MBD, args); return createBean(beanName, MBD, args); } catch (BeansException ex) { destroySingleton(beanName); throw ex; }}); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } } // Check if required type matches the type of the actual bean instance. if (requiredType ! = null && ! requiredType.isInstance(bean)) { try { T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType); if (convertedBean == null) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } return convertedBean; } catch (TypeMismatchException ex) { throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } return (T) bean; }Copy the code
Once I get into the getSingleton() method, I find that it’s all about doing some preparatory work, The real call is lambda expressions org. Springframework. Beans. Factory. Support. DefaultSingletonBeanRegistry# getSingleton (Java. Lang. String, org.springframework.beans.factory.ObjectFactory
)
public Object getSingleton(String beanName, ObjectFactory<? > singletonFactory) { 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!) "); } beforeSingletonCreation(beanName); boolean newSingleton = false; boolean recordSuppressedExceptions = (this.suppressedExceptions == null); if (recordSuppressedExceptions) { this.suppressedExceptions = new LinkedHashSet<>(); } try { singletonObject = singletonFactory.getObject(); newSingleton = true; } catch (IllegalStateException ex) { singletonObject = this.singletonObjects.get(beanName); if (singletonObject == null) { throw ex; } } catch (BeanCreationException ex) { if (recordSuppressedExceptions) { for (Exception suppressedException : this.suppressedExceptions) { ex.addRelatedCause(suppressedException); } } throw ex; } finally { if (recordSuppressedExceptions) { this.suppressedExceptions = null; } afterSingletonCreation(beanName); } if (newSingleton) { addSingleton(beanName, singletonObject); } } return singletonObject; }}Copy the code
In 1 and 2
Enter the lambda expressions in the org. Springframework. Beans. Factory. Support. AbstractAutowireCapableBeanFactory# createBean (Java. Lang. String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException { RootBeanDefinition mbdToUse = mbd; . Class<? > resolvedClass = resolveBeanClass(mbd, beanName); if (resolvedClass ! = null && ! mbd.hasBeanClass() && mbd.getBeanClassName() ! = null) { mbdToUse = new RootBeanDefinition(mbd); mbdToUse.setBeanClass(resolvedClass); } // Prepare method overrides. try { mbdToUse.prepareMethodOverrides(); } catch (BeanDefinitionValidationException ex) { throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex); } try {/ / instantiate the pre-process, AOP functionality is based on the judgment of the Object bean = resolveBeforeInstantiation (beanName mbdToUse); if (bean ! = null) { return bean; } } catch (Throwable ex) { throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex); } try { Object beanInstance = doCreateBean(beanName, mbdToUse, args); return beanInstance; } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) { throw ex; } catch (Throwable ex) { throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex); } } @Nullable protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) { Object bean = null; if (! Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) { // Make sure bean class is actually resolved at this point. if (! mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { Class<? > targetType = determineTargetType(beanName, mbd); if (targetType ! = null) {/ / first place bean = applyBeanPostProcessorsBeforeInstantiation (targetType, beanName); if (bean ! Bean = = null) {/ / second place applyBeanPostProcessorsAfterInitialization (bean, beanName); } } } mbd.beforeInstantiationResolved = (bean ! = null); } return bean; }Copy the code
In the third place
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) { // Candidate constructors for autowiring? Constructor<? >[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName); ...} protected Constructor <? >[] determineConstructorsFromBeanPostProcessors(@Nullable Class<? > beanClass, String beanName) throws BeansException { if (beanClass ! = null && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; Constructor<? >[] ctors = ibp.determineCandidateConstructors(beanClass, beanName); if (ctors ! = null) { return ctors; } } } } return null; }Copy the code
Four, five, eleven
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {··· synchronized (mbd.postProcessingLock) {if (! MBD. PostProcessed) {try {/ / 4 applyMergedBeanDefinitionPostProcessors (MBD, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName)); if (earlySingletonExposure) { if (logger.isTraceEnabled()) { logger.trace("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references"); } addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, MBD, bean)); }... try {/ / 11 Register beans as the disposable. RegisterDisposableBeanIfNecessary (beanName, bean, MBD); } return exposedObject; } protected Object getEarlyBeanReference(String beanName, RootBeanDefinition MBD, Object bean) { Object exposedObject = bean; if (! mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof SmartInstantiationAwareBeanPostProcessor) { SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp; exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName); } } } return exposedObject; }Copy the code
Six, seven, eight
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean
Protected void populateBean(String beanName, RootBeanDefinition MBD, @Nullable BeanWrapper BW) {··· if (! mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) { for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; // if (! ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) { return; } } } } PropertyDescriptor[] filteredPds = null; if (hasInstAwareBpps) { if (pvs == null) { pvs = mbd.getPropertyValues(); } for (BeanPostProcessor bp : getBeanPostProcessors()) { if (bp instanceof InstantiationAwareBeanPostProcessor) { InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp; / / 7 PropertyValues pvsToUse = ibp. PostProcessProperties (PVS, bw. GetWrappedInstance (), beanName); if (pvsToUse == null) { if (filteredPds == null) { filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching); } / / 8 pvsToUse = ibp. PostProcessPropertyValues (PVS, filteredPds, bw. GetWrappedInstance (), beanName); if (pvsToUse == null) { return; } } pvs = pvsToUse; }}}Copy the code
The ninetieth place
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) { if (System.getSecurityManager() ! = null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { invokeAwareMethods(beanName, bean); return null; }, getAccessControlContext()); } else {// Handle the aware interface, set beanname or factory invokeAwareMethods(beanname, bean); } Object wrappedBean = bean; if (mbd == null || ! MBD. IsSynthetic ()) {/ / 9 wrappedBean = applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName); } try { invokeInitMethods(beanName, wrappedBean, mbd); } catch (Throwable ex) { throw new BeanCreationException( (mbd ! = null ? mbd.getResourceDescription() : null), beanName, "Invocation of init method failed", ex); } if (mbd == null || ! MBD. IsSynthetic ()) {/ / 10 wrappedBean = applyBeanPostProcessorsAfterInitialization (wrappedBean, beanName); } return wrappedBean; } // Spring invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd) throws Throwable { boolean isInitializingBean = (bean instanceof InitializingBean); if (isInitializingBean && (mbd == null || ! mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) { if (logger.isTraceEnabled()) { logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'"); } if (System.getSecurityManager() ! = null) { try { AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> { ((InitializingBean) bean).afterPropertiesSet(); return null; }, getAccessControlContext()); } catch (PrivilegedActionException pae) { throw pae.getException(); } } else { ((InitializingBean) bean).afterPropertiesSet(); } } \ if (mbd ! = null && bean.getClass() ! = NullBean.class) { String initMethodName = mbd.getInitMethodName(); if (StringUtils.hasLength(initMethodName) && ! (isInitializingBean && "afterPropertiesSet".equals(initMethodName)) && ! mbd.isExternallyManagedInitMethod(initMethodName)) { invokeCustomInitMethod(beanName, bean, mbd); }}}Copy the code