directory

  • 1. Overview of Bean instantiation
  • 2. Process overview
  • 3. Source code analysis
  • 4. Demonstrate
  • 4. To summarize

Every ounce of effort you put into the source code is worth it.

1. Overview of Bean instantiation

The previous article analyzed the encapsulation process of BeanDefinition, and finally put beanName and BeanDefinition into beanDefinitionMap container in a one-to-one mapping relationship. This article focuses on how to instantiate a bean using its definition information.

2. Process overview

In fact, the bean instantiation process is quite complicated, with many details in the middle. In order to grasp the key points, the core process is sorted out first, mainly including the following processes:

Step1: create instance by reflection; Step2: Assign an initial value to the instance attribute; Step3: If the Bean class implements the BeanNameAware interface, the setBeanName() method is called by passing the Bean name; If the Bean class implements the BeanClassLoaderAware interface, the setBeanClassLoader() method is called by passing an instance of the ClassLoader object that loaded the Bean; If the Bean class implements the BeanFactoryAware interface, the setBeanFactory() method is called by passing an instance of the BeanFactory object; Step4: if there is a class implements BeanPostProcessors interface, will call before initialization postProcessBeforeInitialization () method; Step5: If the Bean class implements the InitializingBean interface, the afterPropertiesSet() method is called. If the Bean definition in the configuration file contains an init-method property, the value of that property is resolved to the name of the method in the Bean class, and the method is called; Step6: if there is a class implements BeanPostProcessors interface, will call after initialization postProcessAfterInitialization () method; Step7: if the Bean class implements the DisposableBean interface, the destroy() method will be called when the Application no longer needs the Bean reference; If the Bean definition in the configuration file contains the destroy-method attribute, the corresponding method definition in the Bean class will be invoked.

3. Source code analysis

Into the fresh AbstractApplicationContext () method, find finishBeanFactoryInitialization (the beanFactory) method, the class is bean instantiation of the entrance, The specific instantiation is triggered by the preInstantiateSingletons() method as shown in the following code:

<code-box id="xHFQpn" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-xHFQpn" class="hljs armasm mCustomScrollbar _mCS_1 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-dCT6nD" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >public void preInstantiateSingletons() throws BeansException if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } // Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be Part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beandefinitionNames); // Trigger initialization of all non-lazy singleton beans... for (String beanName : BeanNames) {/ / father BeanDefinition attributes to get the child BeanDefinition RootBeanDefinition bd = getMergedLocalBeanDefinition (beanName); // instantiate if (! bd.isAbstract() && bd.isSingleton() && ! Bd.islazyinit ()) {if (isFactoryBean(beanName)) {Object bean = getBean(FACTORY_BEAN_PREFIX +)  beanName); if (bean instanceof FactoryBean) { FactoryBean<? > factory = (FactoryBean<? >) bean; boolean isEagerInit; if (System.getSecurityManager() ! = null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged( (PrivilegedAction<Boolean>) ((SmartFactoryBean<? >) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<? >) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); }}} else {// Instantiate process getBean(beanName); } } }</code-pre> </pre></code-box>Copy the code

The code above focuses on the getBean method and then goes to the doGetBean method:

<code-box id="iaxDFz" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-iaxDFz" class="hljs pgsql mCustomScrollbar _mCS_2 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-QA78ZG" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >protected <T> T doGetBean( String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly) throws BeansException { String beanName = transformedBeanName(name); Object bean; Object sharedInstance = getSingleton(beanName); // Get bean.object sharedInstance = getSingleton(beanName); if (sharedInstance ! = null && args == null) { if (logger.isTraceEnabled()) { if (isSingletonCurrentlyInCreation(beanName)) { logger.trace("Returning eagerly cached instance of singleton bean '" + beanName + "' that is not fully initialized yet -  a consequence of a circular reference"); } else { logger.trace("Returning cached instance of singleton bean '" + beanName + "'"); } } bean = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // Fail if we're already creating this bean instance: // We're assumably within a circular reference. if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // Check if bean definition exists in this factory. BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory ! = null && ! containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); if (parentBeanFactory instanceof AbstractBeanFactory) { return ((AbstractBeanFactory) parentBeanFactory).doGetBean( nameToLookup, requiredType, args, typeCheckOnly); } else if (args ! = null) { // Delegation to parent with explicit args. return (T) parentBeanFactory.getBean(nameToLookup, args); } else if (requiredType ! = null) { // No args -> delegate to standard getBean method. return parentBeanFactory.getBean(nameToLookup, requiredType); } else { return (T) parentBeanFactory.getBean(nameToLookup); } } if (! typeCheckOnly) { markBeanAsCreated(beanName); } try { RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); if (dependsOn ! = null) { for (String dep : dependsOn) { if (isDependent(beanName, dep)) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'"); } registerDependentBean(dep, beanName); try { getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); If (mbd.issingleton ()) {sharedInstance = getSingleton(beanName); () -> { try { return createBean(beanName, mbd, args); } catch (BeansException ex) { // Explicitly remove instance from singleton cache: It might have been put there // eagerly by the creation process, to allow for circular reference resolution. // Also remove any beans that received a temporary reference to the bean. destroySingleton(beanName); throw ex; }}); bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); }... }</code-pre> </pre></code-box>Copy the code

As you can see from the above code, the bean is first fetched from the cache. If not, the bean is created. The most important method is getSingleton, whose second argument is a functional interface into the getSingleton method. When calling singletonObject = singletonFactory. GetObject (), will trigger the createBean method in functional interface, then all the way into the doCreateBean, this method has completed all the steps required to instantiate:

<code-box id="fmyDEp" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-fmyDEp" class="hljs processing mCustomScrollbar _mCS_3 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-ZEZrYQ" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {// Instantiate the bean. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { instanceWrapper = createBeanInstance(beanName, mbd, args); } Object bean = instanceWrapper.getWrappedInstance(); Class<? > beanType = instanceWrapper.getWrappedClass(); if (beanType ! = NullBean.class) { mbd.resolvedTargetType = beanType; } // Allow post-processors to modify the merged bean definition. synchronized (mbd.postProcessingLock) { if (! mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } // Eagerly cache singletons to be able to resolve circular references // even when triggered by lifecycle interfaces  like BeanFactoryAware. 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)); } // Initialize the bean instance. Object exposedObject = bean; // Assign the property to populateBean(beanName, MBD, instanceWrapper); // Initialize the bean exposedObject = initializeBean(beanName, exposedObject, MBD); } catch (Throwable ex) { if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) { throw (BeanCreationException) ex; } else { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex); } } if (earlySingletonExposure) { Object earlySingletonReference = getSingleton(beanName, false); if (earlySingletonReference ! = null) { if (exposedObject == bean) { exposedObject = earlySingletonReference; } else if (! this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) { String[] dependentBeans = getDependentBeans(beanName); Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length); for (String dependentBean : dependentBeans) { if (! removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) { actualDependentBeans.add(dependentBean); } } if (! actualDependentBeans.isEmpty()) { throw new BeanCurrentlyInCreationException(beanName, "Bean with name '" + beanName + "' has been injected into other beans [" + StringUtils.collectionToCommaDelimitedString(actualDependentBeans) + "] in its raw version as part of a circular reference, but has eventually been " + "wrapped. This means that said other beans do not use the final version of the " + "bean. This is often the result of over-eager type matching - consider using " + "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example."); }}}} / / Register beans as the disposable. / / it is necessary, the destruction of registered bean try {registerDisposableBeanIfNecessary (beanName, bean, MBD); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }</code-pre> </pre></code-box>Copy the code

See from the above source bean instantiation is mainly divided into the following three steps: step1:bean creation; Step2: Assign a value to the bean properties; Step3: initialize the bean; We then get back exposedObject, a fully instantiated bean that registers the bean’s destruction if necessary. We’ll look at this in more detail, but catch up on the main flow first. Step3 is also an important method. Enter the method:

<code-box id="8HWMzh" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-8HWMzh" class="hljs livescript mCustomScrollbar _mCS_4 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-8EN74w" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >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 {// Activate the aware interface invokeAwareMethods(beanName, bean); } Object wrappedBean = bean; if (mbd == null || ! MBD. IsSynthetic ()) {/ / initializes the pretreatment beanPostProcessor wrappedBean = applyBeanPostProcessorsBeforeInitialization (wrappedBean, beanName); } try {// activate init-method method 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 ()) {/ / initializes the post-processing beanPostProcessor wrappedBean = applyBeanPostProcessorsAfterInitialization (wrappedBean, beanName); } return wrappedBean; }</code-pre> </pre></code-box>Copy the code

According to the above source code, four main steps are sorted out: step1: activate aware interface and complete relevant operations of aware interface; Step2: initialize the beanPostProcessor for pre-processing. Step3: complete init-method method; Step4: initialize the beanPostProcessor for post-processing; BeanPostProcessor enhances the bean after initialization. In this stage, BeanPostProcessor processes all qualified bean objects in the current container after instantiation. It effectively extends the bean instance object provided by the Spring container, allowing Spring to customize the bean during the initialization phase, such as handling the markup interface or providing a proxy implementation for it.

4. Demonstrate

Define a MyBeanPostProcessor to implement the BeanPostProcessor interface

<code-box id="TNQzyj" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-TNQzyj" class="hljs java mCustomScrollbar _mCS_5 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-CyN7jd" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >public class MyBeanPostProcessor implements BeanPostProcessor { @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {system.out. println(" Post Process Before Initialization is called..." ); return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {system.out. println(" Post Process after Initialization is called..." ); return bean; } }</code-pre> </pre></code-box>Copy the code

Define a LifeCycleBean class that implements the following interface:

<code-box id="WiaQRB" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-WiaQRB" class="hljs cs mCustomScrollbar _mCS_6 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-ZG6ZfE" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >public class LifeCycleBean implements BeanNameAware, BeanFactoryAware, BeanClassLoaderAware, InitializingBean, DisposableBean { private String property; public String getProperty() { return property; } public void setProperty(String property) {system.out.println (" property injection....") ); this.property = property; } public LifeCycleBean(){system.out.println (" constructor call... ); } @override public void setBeanClassLoader(ClassLoader ClassLoader) {system.out.println ("BeanClassLoaderAware is called... ); } @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("BeanFactoryAware is called... ); } @override public void setBeanName(String name) {system.out.println ("BeanNameAware was called..." ); } @override public void destroy() throws Exception {system.out.println ("DisposableBean destroy called..." ); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitializingBean afterPropertiesSet Is called..." ); } public void initMethod(){system.out.println ("init-method called... ); } public void destroyMethod(){system.out.println ("destroy-method called..." ); } public void display(){system.out.println (" method call... ); } }</code-pre> </pre></code-box>Copy the code

Specify the configuration file spring. XML and configure the init-method and destroy-method methods

<code-box id="n3hbaF" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-n3hbaF" class="hljs javascript mCustomScrollbar _mCS_7 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-xNSXpG" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" ><bean id="lifeCycle" class="com.wzj.bean.LifeCycleBean" init-method="initMethod" destroy-method="destroyMethod"> <property name="property" value="property"/> </bean> <bean id="myBeanPostProcessor" class="com.wzj.bean.MyBeanPostProcessor" > </bean></code-pre> </pre></code-box>Copy the code

The test classes are as follows:

<code-box id="dzMaNy" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-dzMaNy" class="hljs groovy mCustomScrollbar _mCS_8 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-4hnwjM" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" >@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring.xml"}) public class TestSpring { @Test public void testLifeCycleBean() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); }</code-pre> </pre></code-box>Copy the code

Execution Result:

<code-box id="mndr4h" style="padding: 0px; margin: 10px 0px; color: rgb(34, 34, 34); font-family: -apple-system, &quot; SF UI Text&quot; , Arial, &quot; PingFang SC&quot; , &quot; Hiragino Sans GB&quot; , &quot; Microsoft YaHei&quot; , &quot; WenQuanYi Micro Hei&quot; , sans-serif; The font - size: 15.5 px; font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; Background: rgba(255, 255, 255, 0.9); text-decoration-thickness: initial; text-decoration-style: initial; text-decoration-color: initial; position: relative; display: block;" ><pre id="pre-mndr4h" class="hljs erlang mCustomScrollbar _mCS_9 mCS-autoHide" style="padding: 10px ! important; margin: 5px 15px; overflow: visible; display: block; background: rgb(43, 43, 43); color: rgb(248, 248, 242); touch-action: pinch-zoom; font-size: 14px ! important; font-weight: 400; font-family: &quot; Ubuntu Mono&quot; , monospace ! important; white-space: pre; overflow-wrap: normal; border-radius: 5px ! important; word-break: break-all; counter-reset: itemcounter 0; The line - height: 1.5! important; position: relative;" > <code-pre class="code-pre" id="pre-e4R3km" style="padding: 0px 0px 0px 10px; margin: 0px; position: relative; display: block; left: 30px; border-left: 1px solid rgb(153, 153, 153);" > constructor call... Property injection.... BeanNameAware is called... BeanClassLoaderAware is called... BeanFactoryAware is called... Post Process Before Initialization is called... InitializingBean afterPropertiesSet is called... Init-method is called... Post Process after Initialization is called... DisposableBean destroy called... Destroy-method is called... </code-pre> </pre></code-box>Copy the code

4. To summarize

This paper gives an overview of the beans from the perspective of a beginner’s entire life cycle, and describes the main process, read the source code of the initial stage, the priority to seize the main process, don’t fall in details, and run through cases, writing notes, drawing flow, such as way to deepen understanding, the subsequent will continue to analyze the bean instantiation of the core processes, design idea, etc.