Spring IOC源碼:簡單易懂的Spring IOC 思路介紹
Spring IOC源碼:核心流程介紹
Spring IOC源碼:ApplicationContext刷新前準(zhǔn)備工作
Spring IOC源碼:obtainFreshBeanFactory 詳解(上)
Spring IOC源碼:obtainFreshBeanFactory 詳解(中)
Spring IOC源碼:obtainFreshBeanFactory 詳解(下)
Spring IOC源碼:<context:component-scan>源碼詳解
Spring IOC源碼:invokeBeanFactoryPostProcessors 后置處理器詳解
Spring IOC源碼:registerBeanPostProcessors 詳解
Spring IOC源碼:實例化前的準(zhǔn)備工作
Spring IOC源碼:finishBeanFactoryInitialization詳解
Spring IoC源碼:getBean 詳解
Spring IoC源碼:createBean( 上)
Spring IoC源碼:createBean( 中)
Spring IoC源碼:createBean( 下)
Spring IoC源碼:finishRefresh 完成刷新詳解
上篇文章講解了實例化后,初始化屬性注入過程中屬性值的解析過程及其注入過程,本篇繼續(xù)講解doCreateBean流程中屬性注入后的其它流程,即對bean實例進(jìn)行初始化。
正文populateBean方法執(zhí)行完成后,開始初始化bean。
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {//如果是單例并且是FactoryBean則嘗試移除
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) { //創(chuàng)建Bean實例,通過策略進(jìn)行創(chuàng)建,如果選擇有參構(gòu)造或無參構(gòu)造
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//獲取當(dāng)前實例對象
final Object bean = instanceWrapper.getWrappedInstance();
//當(dāng)前實例的Calss對象
Class>beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) { //設(shè)置當(dāng)前bean定義信息的目標(biāo)類型
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try {//執(zhí)行MergedBeanDefinitionPostProcessor類型后置處理器的postProcessMergedBeanDefinition方法,
//如@Autowire注解,就是通過該后置處理器進(jìn)行解析
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.
//如果是單例,允許循環(huán)依賴,并且beanName正在創(chuàng)建中
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");
}
//包裝成FactoryObject對象,并添加到三級緩存中
addSingletonFactory(beanName, () ->getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try { //初始化過程,進(jìn)行屬性注入。該過程遞歸創(chuàng)建其依賴的屬性。如果A中有B,B中有C,則創(chuàng)建B跟C。
populateBean(beanName, mbd, instanceWrapper);
//該過程執(zhí)行后置處理器的before方法,bean的init方法,后置處理器的after方法,可能會生成新的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) { //從緩存中獲取,因為上面我們將其添加到三級緩存中,從三級緩存中獲取會調(diào)用FactoryObject對象的getObject方法,可能會觸發(fā)AOP代理。返回代理對象
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) { //如果bean對象還是原來的,則將三級緩存中獲取的對象賦值過去
if (exposedObject == bean) {exposedObject = earlySingletonReference;
}
//如果exposedObject在initializeBean方法中被增強 && 不允許在循環(huán)引用的情況下使用注入原始bean實例
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {// 獲取依賴當(dāng)前beanName的所有bean名稱
String[] dependentBeans = getDependentBeans(beanName);
SetactualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
//嘗試移除這些bean的實例,因為這些bean依賴的bean已經(jīng)被增強了,他們依賴的bean相當(dāng)于臟數(shù)據(jù)
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 " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try { //注冊用于銷毀的bean,執(zhí)行銷毀操作的有三種:自定義destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) { throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
initializeBean(beanName, exposedObject, mbd),見方法1詳解
registerDisposableBeanIfNecessary(beanName, bean, mbd),見方法7詳解
方法1:initializeBeanprotected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction
invokeAwareMethods(beanName, bean),見方法2詳解
applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName),見方法3詳解
invokeInitMethods(beanName, wrappedBean, mbd),見方法4詳解
applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName),見方法6詳解
方法2:invokeAwareMethodsprivate void invokeAwareMethods(final String beanName, final Object bean) {//如果實現(xiàn)了Aware接口,根據(jù)實現(xiàn)不同接口,對屬性進(jìn)行填充
if (bean instanceof Aware) { //填充beanName值
if (bean instanceof BeanNameAware) { ((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) { //填充ClassLoader
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) { //填充當(dāng)前beanFactory工廠
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
方法3:applyBeanPostProcessorsBeforeInitializationpublic Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {Object result = existingBean;
//執(zhí)行BeanPostProcessors的postProcessBeforeInitialization方法,可能會返回新的對象值。
for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) { return result;
}
result = current;
}
return result;
}
方法4:invokeInitMethodsprotected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {//判斷是否實現(xiàn)了InitializingBean接口,如果是則調(diào)用afterPropertiesSet方法
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
invokeCustomInitMethod(beanName, bean, mbd),見方法5詳解
方法5:invokeCustomInitMethodprotected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {//獲取配置的init方法名稱
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
//獲取初始化方法
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
//如果找不到則判斷是否強制執(zhí)行,強制則拋異常,非強制則警告提示
if (initMethod == null) { if (mbd.isEnforceInitMethod()) { throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else { if (logger.isTraceEnabled()) {logger.trace("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
}
if (logger.isTraceEnabled()) { logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction
方法6:applyBeanPostProcessorsAfterInitializationpublic Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {//執(zhí)行BeanPostProcessors的postProcessAfterInitialization方法,AOP代理就是在這個步驟進(jìn)行處理的
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) { Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) { return result;
}
result = current;
}
return result;
}
方法7:registerDisposableBeanIfNecessaryprotected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
//如果不是多例&&需要銷毀
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) { //如果是單例
if (mbd.isSingleton()) { // Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
//
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else { // A bean with a custom scope...
//根據(jù)自定義的Scope ,注冊銷毀回調(diào)方式
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
requiresDestruction(bean, mbd),見方法8詳解
方法8:requiresDestructionprotected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {//當(dāng)前bean不是null
// 1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判斷bean是否有destroy方法
// 2.hasDestructionAwareBeanPostProcessors():判斷當(dāng)前BeanFactory是否注冊過DestructionAwareBeanPostProcessor
// 3.DisposableBeanAdapter.hasApplicableProcessors:是否存在適用于bean的DestructionAwareBeanPostProcessor
return (bean.getClass() != NullBean.class &&
(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}
DisposableBeanAdapter.hasDestroyMethod(bean, mbd),見方法9詳解
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()),見方法10詳解
public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {//bean實現(xiàn)了DisposableBean 或AutoCloseable接口
if (bean instanceof DisposableBean || bean instanceof AutoCloseable) { return true;
}
//獲取銷毀方法名稱
String destroyMethodName = beanDefinition.getDestroyMethodName();
//如果自定銷毀方法名稱為 "(inferred)"
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) { //判斷是否有close或shutdown方法
return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
}
return StringUtils.hasLength(destroyMethodName);
}
方法10:hasApplicableProcessorspublic static boolean hasApplicableProcessors(Object bean, ListpostProcessors) {if (!CollectionUtils.isEmpty(postProcessors)) { //遍歷后置處理器
for (BeanPostProcessor processor : postProcessors) { //如果有類型為DestructionAwareBeanPostProcessor的后置處理器
if (processor instanceof DestructionAwareBeanPostProcessor) {DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
//判斷是否需要由這個后置處理器進(jìn)行銷毀
if (dabpp.requiresDestruction(bean)) {return true;
}
}
}
}
return false;
}
總結(jié)到此,整個bean的創(chuàng)建流程就結(jié)束了。
1、對當(dāng)前Bean實現(xiàn)不同的Aware接口,對不同的屬性值進(jìn)行填充
2、執(zhí)行BeanPostProcessors的postProcessBeforeInitialization方法,可能會返回新的對象值。
3、調(diào)用執(zhí)行自定義的初始化方法,如果當(dāng)前Bean實現(xiàn)了InitializingBean接口,則調(diào)用afterPropertiesSet方法
4、執(zhí)行BeanPostProcessors的postProcessAfterInitialization方法,AOP代理就是在這個步驟進(jìn)行處理的
5、注冊銷毀相關(guān)方法,會在IOC銷毀流程中進(jìn)行回調(diào)。
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧