Spring IoC原理详解之一prepareRefresh
bean实例化是IoC容器非常非常非常重要的功能,解释起来也非常麻烦。分为两篇介绍,本篇紧接着前一篇:
AbstractAutowireCapableBeanFactory#createBean
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 通过Class.forName(bean)方法获取实例,合并bean定义
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
// 设置重写属性值:setOverloaded(false)
// @LookUp注解就是在这里实现的
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
/**
* 执行后置处理器
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor 接口实现类,
* 给一个机会返回代理对象而不是目标bean实例本身,如果是AOP类就会在这里返回了,比如用@Aspect注释的类
* 此接口通常是Spring框架内部使用,这个接口的功能非常强大,使用起来难度大,主要是它继承了很多后置处理接口,导致里面的方法很多(一共有6个方法需要实现)。
* 如果开发者也想使用此接口的功能推荐使用它的抽象实现InstantiationAwareBeanPostProcessorAdapter。继承此类重写其中你需要的方法即可,
* 这个抽象类做了一些默认实现不需要你实现9个方法,重写你要的就行了。
* 注意:如果这里返回了代理对象,则直接结束当前方法返回,不继续往下执行doCreateBean创建普通实例,doCreateBean里面进行的属性填充后置处理器也不会执行。
* @see #resolveBeforeInstantiation
*/
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
// 根据BeanDefinition创建bean,并且对创建好的bean执行框架定义的+用户定义的各种后置处理器对bean增强。
// 同时也会进行属性的填充,执行初始化回调方法,执行XxxAware接口
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
/**
* 回到调用处:
* @see AbstractBeanFactory#doGetBean(String, Class, Object[], boolean)
*/
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
这个方法完成两个事情,一是提供一个创建代理的机会,二,不创建代理的情况调用doCreateBean(beanName, mbdToUse,args)方法创建对象。
doCreateBean(beanName, mbdToUse, args);
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 从缓存中查询,如果是bean定义是一个bean工厂实例可以直接拿到。
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 普通bean,根据bean定义创建bean实例,并包装成BeanWrapper返回
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 获取经过jdk1.8的Optional类包装过的非空对象
final Object bean = instanceWrapper.getWrappedInstance();
// 获取bean的class类型
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// 执行后置处理器接口MergedBeanDefinitionPostProcessor,bean实例化之后,就可以通过反射获取到类或者属性上的注释信息
// 处理@Resource、@Autowired、@Value注解的定义信息,并把这些注解的定义信息放在缓存中。待后续属性填充的时候使用。
// 如果有则吧注解信息转换成AutowiredFieldElement对象或者AutowiredMethodElement对象或者ResourceElement对象
// 实现类有:AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor等
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.
// 单例bean && 允许循环依赖 && bean正在被创建
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");
}
/**
* 执行后置处理器SmartInstantiationAwareBeanPostProcessor的getEarlyBeanReference()方法尝试获取一个早期的引用。
* 并加入的单例工厂缓存中
* @see DefaultSingletonBeanRegistry#addSingletonFactory(String, ObjectFactory)
* @see #getEarlyBeanReference
*/
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
// 初始化bean实例,填充属性,注入依赖(@Autowired,@Resource,@Value)注解的属性
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
/**
执行bean的初始化回调方法以及执行后置处理器的初始化方法,包括:
一,执行Aware接口 ,包括BeanFactoryAware,BeanClassLoaderAware,BeanNameAware
注意:ApplicationContext的注入是在另外一个后置处理器ApplicationContextAwareProcessor中执行。
二,执行bean初始化回调,包括:
0. 执行初始化回调BeanPostProcessor.postProcessBeforeInitialization()方法
1. 执行初始化回调@PostConstruct注解定义的方法
2. 执行初始化回调InitializingBean.afterPropertiesSet()方法
3. 执行初始化回调@Bean(initMethod = "beanInit")定义的初始化方法beanInit()
4. 执行初始化回调BeanPostProcessor.postProcessAfterInitialization()方法
5. 执行初始化回调SmartInitializingSingleton.afterSingletonsInstantiated()方法
按照上述执行顺序执行
*/
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) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
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销毁回调方法,这个方法和前面的initializeBean()方法是对应的。通常情况下初始化方法和销毁方法是同时出现的。
* 比如回调DisposableBean接口的destroy()方法,需要注意的是这里只是注册,并不会执行销毁回调方法。
* 销毁方法的调用是在手动执行容器的关闭方法的时候:
* @see org.springframework.context.support.AbstractApplicationContext#close()
*
* @see AbstractBeanFactory#registerDisposableBeanIfNecessary(String, Object, RootBeanDefinition)
*/
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
/**
* 回到调用处:
* @see #createBean(String, RootBeanDefinition, Object[])
*/
return exposedObject;
}
这个方法非常复杂,完成对象创建,属性填充,依赖注入,初始化。
- createBeanInstance(beanName, mbd, args)方法完成对象创建
- applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)方法完成@Resource、@Autowired、@Value注解的定义信息加载。
- addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))方法尝试获取一个早期的引用
- populateBean(beanName, mbd, instanceWrapper)方法执行后置处理器的postProcessAfterInstantiation()方法,完成@Autowired,@Resource,@Value注解的属性值注入。
- initializeBean(beanName, exposedObject, mbd)方法执行各种初始化回调方法
- registerDisposableBeanIfNecessary(beanName, bean, mbd)方法完成bean的各种销毁方法的注册
1. createBeanInstance(beanName, mbd, args)
这个方法最底层是通过反射的newInstance()方法创建对象。
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
// 检查bean的访问类型,比如是public并且是非final
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
// 存在Supplier回调则使用回调里的方法创建实例(jdk1.8)之后的才有的特性
// 通过instanceSupplier.get()方法返回实例
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
// 通过工厂方法创建实例
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
// 通过constructorArgumentsResolved标记起到了缓存的作用
// 当容器创建同一个类型bean的时候(非单例情况),可以直接使用构造器创建,不需要再此解析构造器上的参数。
// 参数的解析的开销也是不小的。
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
// constructorArgumentsResolved标记了构造器的参数都已经解析完成
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
/**
* 通过有参构造方法创建,并自动注入构造方法中的参数值,如果有对象依赖在方法内部又会调getBean()方法创建bean实例
* 然后注入到对应的属性上。比如这个bean,构造方法引用了另外一个RefrenceBeanA
* @see com.ubuntuvim.spring.createbean.HasArgsConstructBean
* <pre>
* @Component
* public class HasArgsConstructBean {
* private RefrenceBeanA refrenceBeanA;
*
* public HasArgsConstructBean(RefrenceBeanA refrenceBeanA) {
* this.refrenceBeanA = refrenceBeanA;
* }
* }
* </pre>
*/
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认的无参构造方法创建实例,底层使用反射newInstance()方法创建对象
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
/**
* 如果有依赖注入的构造器
* 方法内部会调用后置处理器获取定制化的构造器列表,如果没有任何后置处理器的实现则返回null
* @see SmartInstantiationAwareBeanPostProcessor
*/
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
// 如果有默认的构造器
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
/**
* 前面的构造器都没有则最后使用无参构造器创建实例
* 底层使用反射newInstance()方法创建对象
* 实例创建完成,回到调用处:
* @see AbstractAutowireCapableBeanFactory#doCreateBean(String, RootBeanDefinition, Object[])
*/
return instantiateBean(beanName, mbd);
}
instantiateBean()方法的代码我就不贴了,底层使用反射newInstance()方法创建对象。
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName)
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
这个方法比较简单,就是执行容器中后置处理器MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition()方法。
这个后置处理器有两个非常重要的实现类。一个是AutowiredAnnotationBeanPostProcessor,一个是CommonAnnotationBeanPostProcessor,这两个后置处理器的实现在这里主要是用来扫描@Resource、@Autowired、@Value注解的定义信息
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean))
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 获取提前暴露的bean引用,主要用于解决循环依赖,只有单例bean调用此方法
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
populateBean(beanName, mbd, instanceWrapper)
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 前面创建的bean实例为空时
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
// 当前bean实例都是null也就无法填充属性值了,直接返回
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 执行后置处理器InstantiationAwareBeanPostProcessor,提供一个机会让开发者可以在bean实例化后,初始化前做一些操作。
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 如果返回false则直接退出当前方法,不进行下面的属性填充操作,所以一定要非常注意后置处理器的返回值以及执行顺序。
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
// 获取属性值
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
// 获取注入模式(byType或者byName)
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 把属性值再做一次包装,转换成一个MutablePropertyValues对象。
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 如果适用,根据类型添加基于自动装配的属性值。
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 如果适用,根据类型添加基于自动装配的属性值。
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 存在InstantiationAwareBeanPostProcessor后置处理器
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
// 依赖注入模式不是byType或者byName的情况有可能为空,这两种情况执行了pvs = newPvs不会为null
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
/**
* 属性注入,包括依赖对象注入,依赖集合注入,
* 比如下面这3种写法,都会在此完成属性注入
* <pre>
* @Autowired
* private Fruit apple;
*
* @Autowired
* private List<InterfaceA> interfaceAList;
*
* 同理,Map也是一样的
* @Autowired
* private Map<String, InterfaceA> interfaceAMap;
* key就是实现类的beanName,value就是实现类实例对象。
* </pre>
* 其中AutowiredAnnotationBeanPostProcessor这个后置处理器用于给@Autowired注解或者@Value注解定义的属性注入值,
* 注入的步骤:1. 扫描bean实例中使用@Autowired注解的属性和方法,2. 根据注入的类型从IoC容器中在匹配的bean;3. 通过反射执行赋值操作
* @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessProperties
* @see org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor#postProcessPropertyValues
*
* 其中CommonAnnotationBeanPostProcessor这个后置处理器用于给@Resource注解定义的属性注入值
* 同时这个类还处理了@PostConstruct/@PreDestroy这两个注解
* @see org.springframework.context.annotation.CommonAnnotationBeanPostProcessor#postProcessProperties
*/
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessProperties()方法已经声明为过时。推荐使用postProcessPropertyValues()方法
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
// 如果返回的属性值为null直接退出当前方法,说明没有可填充的属性
// 在实现后置处理器的时候特别要注意接口方法的返回值已经执行顺序,如果第一个后置处理器就返回了null,
// 那么同一类型的其他排在后面的就不会执行了
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
// 是否需要依赖检查,DEPENDENCY_CHECK_NONE标识不需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
/**
* 处理xml方式的<property>标签。比如下面的bean
* <bean id="testBean" class="com.ubuntuvim.spring.TestBean">
* <property name="name" value="ubuntuvim" />
* <property name="address" value="china" />
* </bean>
*/
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
这个方法实现也是非常复杂的,它所完成的事情在代码的注释上已经有说明。
initializeBean(beanName, exposedObject, mbd)
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 如果bean实现了XxxAware接口,则调用这些接口的setXxx()方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}
/**
* 执行后置处理器的postProcessorBeforeInitialization()方法
* 这里会首先执行第一个初始化回调@PostConstruct声明的方法,是这个类实现的
* @see org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor#postProcessBeforeInitialization
*/
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
// 执行InitializingBean接口和自定义的初始化方法(@Bean(initMethod = "beanInit"))
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
/**
* 执行后置处理器的postProcessorAfterInitialization()方法
*/
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
/**
* 完成各种初始化回调方法,回到调用处:
* @see #doCreateBean(String, RootBeanDefinition, Object[])
*/
return wrappedBean;
}
这个方法主要完成属性的填充,依赖注入。详细过程代码注释已经有描述。
registerDisposableBeanIfNecessary(beanName, bean, mbd)
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// 非原型bean && (bean实例内使用里@PreDestory注解 || bean实现了DisposableBean接口
// || 容器中注册了DestructionAwareBeanPostProcessor后置处理器)
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
// 单例bean
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
/**
* 把销毁回调方法包装成DisposableBeanAdapter并注册到容器中,待手动调用容器的close()方法的时候执行
* 包括:
* 1. @Bean注解中自定义的销毁回调方法
* 2. @PreDestory注解的回调方法
* 3. 实现DispoableBean接口的detory()回调方法
* 4. 后置处理器DestructionAwareBeanPostProcessor的postProcessBeforeDestruction()方法
*/
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
// 非单例、非原型bean
else {
// A bean with a custom scope...
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));
}
}
}
到处完成普通对象的创建、初始化、执行初始回调等操作。
AbstractBeanFactory.getObjectForBeanInstance()
第二个方法是当前类实现的:AbstractBeanFactory.getObjectForBeanInstance()
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
// 如果不是FactoryBean,为了以防开发者自定义的bean名字也加了&前缀,因为Spring默认&开头的bean是工厂bean
if (BeanFactoryUtils.isFactoryDereference(name)) {
if (beanInstance instanceof NullBean) {
return beanInstance;
}
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
if (mbd != null) {
mbd.isFactoryBean = true;
}
return beanInstance;
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
// 如果不是FactoryBean则无需通过调用getObject方法获取实例,
// 正常情况下普通的bean已经在前面的doCreateBean方法中创建好了
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
// 从FactoryBean对象缓存中获取
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
// 获取工厂bean实例本身
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
// 调用工厂bean的getObject方法获取对象实例
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
前面一大推都是判断和校验,真正创建实例对象是在getObjectFromFactoryBean()方法中。
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// FactoryBean接口中的isSingleton()方法返回的值作用是:
// 由FactoryBean创建出来的bean实例的作用域是singleton还是prototype,
// 如果返回false,表示由这个FactoryBean创建的对象是多例的,
// 那么我们每次从容器中getBean的时候都会去重新调用FactoryBean中的getObject方法获取一个新的对象。
// 若返回true,表示创建的对象是单例的,那么我们每次从容器中获取这个对象的时候都是同一个对象(直接从单例缓存中获取)。
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
Object object = this.factoryBeanObjectCache.get(beanName);
if (object == null) {
// 调用工厂bean的getObject方法获取对象实例
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
/**
* 调用子类的实现。用于执行后置处理器,对bean实例做增强。
* @see AbstractAutowireCapableBeanFactory#postProcessObjectFromFactoryBean
*/
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
// 如果FactoryBean接口中的isSingleton()方法返回的是true,
// 表示通过工厂bean创建出来的bean对象不是单例的,所以不需要缓存每次都是创建一个新的对象实例
else {
// 调用工厂bean的getObject方法获取对象实例
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
/**
* 调用子类的实现。用于执行后置处理器,对bean实例做增强。
* @see AbstractAutowireCapableBeanFactory#postProcessObjectFromFactoryBean
*/
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
然后创建的逻辑还没到!!具体处理逻辑通常都是放在do开头的方法中。从上面的代码可以看出来FactoryBean接口的提供的方法其实针对的是接口创建出来的bean对象,而不是对工厂实例本身的设置。
比如接口中的isSingleton()方法,设置的是工厂创建出来的bean是单例(返回值是true)的还是非单例的。
private Object doGetObjectFromFactoryBean(final FactoryBean<?> factory, final String beanName)
throws BeanCreationException {
Object object;
try {
// 调用工厂bean的getObject方法获取对象实例
if (System.getSecurityManager() != null) {
AccessControlContext acc = getAccessControlContext();
try {
object = AccessController.doPrivileged((PrivilegedExceptionAction<Object>) factory::getObject, acc);
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
object = factory.getObject();
}
}
catch (FactoryBeanNotInitializedException ex) {
throw new BeanCurrentlyInCreationException(beanName, ex.toString());
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "FactoryBean threw exception on object creation", ex);
}
// Do not accept a null value for a FactoryBean that's not fully
// initialized yet: Many FactoryBeans just return null then.
// 不接受null对象,如果开发者实现了FactoryBean接口,但是在getObject方法中返回了null,那么Spring会默认返回的一个NullBean对象实例
if (object == null) {
if (isSingletonCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(
beanName, "FactoryBean which is currently in creation returned null from getObject");
}
object = new NullBean();
}
return object;
}
这个方法的逻辑就非常简单了,最核心就一句代码factory.getObject()调用工厂bean的getObject()方法获取对象实例。
整个获取对象实例的过程和前面的getSingleton方法类似的,只是最后调用的工厂方法不一样,一个是调用ObjectFactory.getObject()方法创建普通实例对象,一个是调用FactoryBean.getObject()方法创建复杂实例对象。
对象创建完毕之后都会调用一大推的后置处理器。这些后置处理器会在bean的初始化前后做一些处理。
到此完成所有单例对象的创建并做初始化、属性的填充。也就是AbstractApplicationContext.finishBeanFactoryInitialization()方法才执行完。