javascript
Spring Ioc源码分析 之 Bean的加载(7):初始化
接著分析doCreateBean()的第6步——初始化 bean 實例對象
首先回顧下CreateBean的主流程:
一、初始化
Spring在對Bean進行屬性填充之后,會對Bean進行初始化,代碼如下:
//AbstractAutowireCapableBeanFactory.javaprotected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {//JDK的安全機制驗證權限if (System.getSecurityManager() != null) {// <1> 激活 Aware 方法,對特殊的 bean 處理:Aware、BeanClassLoaderAware、BeanFactoryAwareAccessController.doPrivileged((PrivilegedAction<Object>) () -> {invokeAwareMethods(beanName, bean);return null;}, getAccessControlContext());}else {// <1> 激活 Aware 方法,對特殊的 bean 處理:Aware、BeanClassLoaderAware、BeanFactoryAwareinvokeAwareMethods(beanName, bean);}Object wrappedBean = bean;// <2> 后置處理器,beforeif (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);}// <3> 激活用戶自定義的 init 方法try {invokeInitMethods(beanName, wrappedBean, mbd);}catch (Throwable ex) {throw new BeanCreationException((mbd != null ? mbd.getResourceDescription() : null),beanName, "Invocation of init method failed", ex);}// <2> 后置處理器,afterif (mbd == null || !mbd.isSynthetic()) {wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);}return wrappedBean;}初始化 bean 的方法其實就是三個步驟的處理,而這三個步驟主要還是根據用戶設定的來進行初始化,這三個過程為:
- 1.1、Aware
Aware ,英文翻譯是意識到的,感知的。Spring 提供了諸多 Aware 接口,用于輔助 Spring Bean 以編程的方式調用 Spring 容器,通過實現這些接口,可以增強 Spring Bean 的功能。
Spring 提供了如下系列的 Aware 接口:
- 1.2、后置處理器
BeanPostProcessor 在前面介紹 bean 加載的過程曾多次遇到,
它的作用是:
如果我們想要在 Spring 容器完成 Bean 的實例化,配置和其他的初始化后添加一些自己的邏輯處理,那么請使用該接口,這個接口給與了用戶充足的權限去更改或者擴展 Spring,是我們對 Spring 進行擴展和增強處理一個必不可少的接口。
applyBeanPostProcessorsBeforeInitialization() 方法,代碼如下:
applyBeanPostProcessorsAfterInitialization() 方法,代碼如下:
// AbstractAutowireCapableBeanFactory.java @Override public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)throws BeansException {Object result = existingBean;// 遍歷 BeanPostProcessorfor (BeanPostProcessor processor : getBeanPostProcessors()) {// 處理Object current = processor.postProcessAfterInitialization(result, beanName);// 返回空,則返回 resultif (current == null) {return result;}// 修改 resultresult = current;}return result; }其邏輯就是通過 getBeanPostProcessors() 方法,獲取定義的 BeanPostProcessor ,然后分別調用其 postProcessBeforeInitialization() 和 postProcessAfterInitialization() 方法,進行自定義的業務處理。
- 1.3、自定義init方法
在xml中有一個< bean >標簽的配置, init-method 方法,是可以讓我們在Bean初始化的時候,先執行我們自定義的一些邏輯。
其實就是在這里被觸發的,代碼如下:
首先,檢查是否為 InitializingBean 。如果是的話,需要執行 afterPropertiesSet() 方法,因為我們除了可以使用 init-method 來自定初始化方法外,還可以實現 InitializingBean 接口。接口僅有一個 afterPropertiesSet() 方法。
兩者的執行先后順序是先 :<1> 的 #afterPropertiesSet() 方法
后 <2> 的 init-method 對應的方法。
本文轉自:https://cloud.tencent.com/developer/article/1521203
總結
以上是生活随笔為你收集整理的Spring Ioc源码分析 之 Bean的加载(7):初始化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 朋友圈为何总给我推HERMES?
- 下一篇: 好的产品经理都是这样绘制原型图的...