[Spring源码阅读] Spring bean创建后的填充populate

843 阅读1分钟

阅读下面的源码可以看到,Spring在创建完成bean instance后,在populateBean中完成对bean instance的填充

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
     // 1. spring创建bean实例
    BeanWrapper instanceWrapper = createInstance(beanName,mbd, args);
    // 2. 
    applyMergedBeanDefinitionPostProcessors(mbd,beanType,beanName);
    // 3. eagerly cache bean instance 
    // 4. 填充bean
    populateBean(beanName, mbd, instanceWrapper);
    // ......其他操作
}

进入populateBean()了解具体的bean instance填充过程:

//不完全伪代码表示
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    // 1. InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation常用于自定义的field injection
   if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (InstantiationAwareBeanPostProcessor ibp in getBeanPostProcessors()) {
           if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                // 后续的InstantiationAwareBeanPostProcessor也不会对bean instance进行处理了
                continueWithPropertyPopulation = false;
                break;
        	}
        }
   }
   
    //不在继续属性填充,下一步:initializeBean
   if (!continueWithPropertyPopulation) {
	return;
   }
   
   // 2. Spring自动装配
   // byName自动装配
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
        autowireByName(beanName, mbd, bw, newPvs);
    }
    // byType自动装配
    if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
        autowireByType(beanName, mbd, bw, newPvs);
    }
    
    // 3. 
}
1. postProcessAfterInstantiation
2. autowire
3. postProcessProperties
Field Injetion Vs autowire

Quetion: 在springz中,字段注入(field Injection)和自动装配(autowireByName or Type)有什么不一样?