Spring在正常創(chuàng)建Bean的時(shí)候,實(shí)際上是調(diào)用了createBean方法中的doCreateBean方法。
createBean方法關(guān)鍵源碼如下:
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
。。。
try {
//讓InstantiationAwareBeanPostProcessor有機(jī)會(huì)返回代理而不是目標(biāo)bean實(shí)例
//實(shí)際上就是調(diào)用:
// applyBeanPostProcessorsBeforeInstantiation 內(nèi)部for循環(huán)調(diào)用postProcessBeforeInstantiation
// applyBeanPostProcessorsAfterInitialization 內(nèi)部for循環(huán)調(diào)用postProcessAfterInitialization
// 上述兩個(gè)具體的方法主要就是進(jìn)行代理,實(shí)例化前和初始化后作一些增強(qiáng)性的操作,影響bean的創(chuàng)建流程
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) { //如果不為空,說(shuō)明有了代理類(lèi)
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
//spring正常利用構(gòu)造器創(chuàng)建對(duì)象的流程
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
。。。
}
InstantiationAwareBeanPostProcessor使用場(chǎng)景
當(dāng)不想使用spring默認(rèn)創(chuàng)建bean的方法通過(guò)構(gòu)造器創(chuàng)建bean,比如Mybatis的Mapper,它只有接口,沒(méi)有實(shí)現(xiàn)類(lèi)的構(gòu)造方法,postProcessBeforeInstantiation就是在spring使用構(gòu)造器幫你創(chuàng)建bean之前創(chuàng)建對(duì)象的,你可以創(chuàng)建一個(gè)代理對(duì)象返回,那么就可以實(shí)現(xiàn)自定義實(shí)例化對(duì)象了。
doCreateBean方法關(guān)鍵源碼如下:
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
。。。
//這里開(kāi)始對(duì)bean進(jìn)行初始化
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);// 對(duì)屬性賦值
exposedObject = initializeBean(beanName, exposedObject, mbd); // 對(duì)bean進(jìn)行初始化
}
。。。
initializeBean方法關(guān)鍵源碼如下:
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
。。。
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 執(zhí)行后置處理器 before
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
//執(zhí)行用戶自定義的 init 方法
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()) {
// 執(zhí)行后置處理器 after
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
invokeInitMethods方法關(guān)鍵源碼如下:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 是否實(shí)現(xiàn)了 InitializingBean 接口
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 {
// 直接調(diào)用 afterPropertiesSet()
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
// 判斷是否指定了 init-method(),
// 如果指定了 init-method(),則再調(diào)用制定的init-method
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}