//执行BeanPostProcessor.postProcessBeforeInitialization()
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);//执行init方法
invokeInitMethods(beanName, wrappedBean, mbd);//执行BeanPostProcessor.postProcessAfterInitialization()
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
说过applyBeanPostProcessorsBeforeInitialization之后,下面继续看invokeInitMethods(beanName, wrappedBean, mbd);
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);、
//从这块代码中,执行init方法也可以让类实现InitializingBean接口,实现其afterPropertiesSet方
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
@Override
public Object run() throws Exception {
((InitializingBean) bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}
//执行到这里
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//通过反射机制执行其init方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
通过以上代码,就是从类定义信息中获取注解中init的方法名,然后通过反射机制执行其方法
关于类定义信息的初始化,看这里https://blog.youkuaiyun.com/Bandeo/article/details/104222124