本篇文章,我们重点看下一个bean是如何被bean工厂实例化的。
在上两篇文章中,我们对以下3个方法做了流程上的大致分析。
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
//1.会首先调用父类GenericApplicationContext中的构造方法,初始化工厂bean为new DefaultListableBeanFactory()
//2.调用自己的构造方法,初始化了一个读取器:AnnotatedBeanDefinitionReader reader;一个扫描器:ClassPathBeanDefinitionScanner scanner
//3.在reader的初始化构造方法中,还注册了6个post processors
this();
//注册bean,注册就是把bean的定义都放在某个地方,一个并发map中,Map beanDefinitionMap
//这调用了AnnotatedBeanDefinitionReader reader的注册方法
register(annotatedClasses);
//实例化bean
refresh();
}
其中refresh()方法中涉及到bean的实例化,发生在BeanFactory中。
比如在2.4.1.1节中,for循环实例化postProcessorName,其中有一行代码如下:
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)就是使用bean工厂获取bean,如果bean还没有被实例化,这里会进行实例化,本节就针对此过程进行详细分析。
第一篇文章spring5源码阅读(一)中,在分析this()方法时,我们知道spring默认初始化的bean工厂默认是DefaultListableBeanFactory。
先看下类图:
继承了AbstractBeanFactory,此类实现了bean工厂的大部分接口,包括上面例子中说的getBean方法。
AbstractBeanFactory中的getBean,共重写了如下4种:
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
public <T> T getBean(String name, @Nullable Class<T> requiredType, @Nullable Object... args)
throws BeansException {
return doGetBean(name, requiredType, args, false);
}
从上述代码中发现,每种都是基于doGetBean(name, null, args, false)实现的;所以下面我们重点分析doGetBean。
此方法稍微有点长,拆分一下。
此段逻辑关键是getSingleton方法,就是先根据bean的名字从单例池中查询到bean的单例,如果存在就直接返回了。
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//这里已经完成了代理方法
//根据bean名字得到单例,就是从一个叫做单例池那个map中get;
// 这里最开始get出来的肯定是null,因为我们前面一路分析下来,并没有发现哪里往map中put
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
} else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 如果是普通bean直接返回,工厂bean则返回sharedInstance.getObject();
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
//省略。。。
其中getSingleton方法代码如下:
public Object getSingleton(String beanName) {
return getSingleton(beanName, true);
}
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
//singletonObjects是个map,称作单例池;将里面key是beanName的实例取出
Object singletonObject = this.singletonObjects.get(beanName);
//isSingletonCurrentlyInCreation判断是否正在创建,正在创建的bean都是放在singletonsCurrentlyInCreation的Set中
//只需要看看set集合中有没有就行了
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
getSingleton的入参allowEarlyReference默认为true,表示允许循环依赖;
this.singletonObjects表示单例池,是个map,所有实例化的单例都会缓存在这里。属于上下文容器的一部分。
this.earlySingletonObjects表示早期bean单例池,这个early的含义就是指bean刚实例化,但是还没有初始化,比如没有设置bean的属性值;用于解决循环依赖。循环依赖的详细说明,见下一篇文章spring5源码阅读(四)如何解决循环依赖
目前这个bean还没有被实例化过,所以getSingleton返回的是null,继续进入下一节分析。
从单例池中没有得到单例,接下来进入else中,
//省略。。。
} else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//校验是否存在bean的定义,这里是存在的,进不到if中
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
} else if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
} else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
//标记此bean正在或者已经被创建了
markBeanAsCreated(beanName);
}
//省略。。。
这段没啥好看的,继续往下,
//省略。。。
try {
//获取bean的定义描述信息,比如是否单例,注解等信息
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//抽象bean不实例化,直接抛异常
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
//这里是得到用了@DependsOn注解标记的类,就是依赖的类
//确保依赖的bean已经被实例化
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
//是否循环依赖
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册依赖和被依赖关系;就是放到map中
registerDependentBean(dep, beanName);
try {
//实例化依赖bean
getBean(dep);
} catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
//省略。。。
这段是在处理 @DependsOn注解,解决循环依赖。比如有A/B/C 3个类,A类上使用@DependsOn(“b”),表示A依赖B;
@Component
@DependsOn("b")
public class A {
}
@Component
@DependsOn("c")
public class B {
}
@Component
@DependsOn("a")
public class C {
}
这样就是A依赖B,B依赖C,C依赖A,形成了循环依赖,这段代码就是spring判断是否存在这种情况,存在就会抛异常;
如果不存在循环依赖,但是确实存在依赖的bean,比如在实例化A的时候,发现依赖B,那么就会先实例化B类。
上面处理完了通过@DependsOn依赖的bean,接下来就是真正实例化当前bean了。
下面这段代码主要是判断将要实例化的bean类型,比如单例/prototype和其他,针对不同的类型进行不同的处理方式。
这里我们主要针对单例类型进行分析。
第二行getSingleton,上面分析了一种实现,这个方法有好几个重载,这个方法多了个参数,用来延迟执行createBean。
//省略。。。
// Create bean instance.
if (mbd.isSingleton()) {
//创建出对象
//如果是代理模式,创建代理对象
sharedInstance = getSingleton(beanName, () -> {
//这里实现了ObjectFactory的getObject()方法
try {
//创建bean,如果有代理,则创建代理对象
return createBean(beanName, mbd, args);
} catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
} finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
} catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
} catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
//省略。。。
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
synchronized (this.singletonObjects) {
//从单例池中取出单例,开始初始化的时候,这个肯定是null
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//确保bean之前没有正在创建中,并记录状态
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
//这里开始创建bean实例
singletonObject = singletonFactory.getObject();
newSingleton = true;
} catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
//抛异常了,再次尝试从单例池中获取一次
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
} catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
} finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//之前把正在创建的bean缓存起来了,现在清除缓存
afterSingletonCreation(beanName);
}
if (newSingleton) {
//将新创建的单例bean,放到单例池中
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
看看 createBean方法,
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("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<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
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.
//在bean实例化前后,执行InstantiationAwareBeanPostProcessor 的回调方法,如果有的话
//并返回代理类
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 {
//创建bean
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
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);
}
}
1.判断是否有自己实现aop,有则创建代理类
2.没有就调用继续实例化bean的方法,如果有,比如添加了切面,也会返回代理类。
先看Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
此方法作用是,在bean实例化前后,给我们一个机会,去执行实现了InstantiationAwareBeanPostProcessor 的回调方法,如果有实现代理的话,返回代理类。
正常情况下是返回null的,除非我们自己实现了InstantiationAwareBeanPostProcessor的接口方法,并在其中实现了动态代理。
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
//beforeInstantiationResolved一般是null,只要不是false就进入if
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
//isSynthetic判断是否合成的bean,即不是应用自己定义的bean
//用于判断beangongc是否有InstantiationAwareBeanPostProcessor后置处理器,用于创建代理的
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
上面如果我们没有自己实现InstantiationAwareBeanPostProcessor接口,那么代码就会继续往下走到doCreateBean方法中。
这个方法是真正创建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()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//实例化,就是使用构造方法创建bean
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//这里还是target bean
final Object bean = instanceWrapper.getWrappedInstance();
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回调方法
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.
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//用于解决循环依赖的设置
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
//初始化bean
Object exposedObject = bean;
try {
//填充bean的属性
populateBean(beanName, mbd, instanceWrapper);
//这里发生了代理关系
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 {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
doCreateBean方法主体流程:
1.首先使用bean的构造方法创建bean;
2.执行MergedBeanDefinitionPostProcessor类型的后置处理器回调方法,利用反射技术,遍历类中的属性和方法,并判断属性和方法上的注解信息;
比如CommonAnnotationBeanPostProcessor.java,用于发现并缓存@Resource等注解修饰的属性;
比如AutowiredAnnotationBeanPostProcessor.java,用于发现并缓存@Autowired/@Value等注解修饰的属性;
等等。
3.提前缓存earlyBeanReference引用,就是实例化还没初始化的bean信息,用于后边处理循环依赖。
4.populateBean填充bean,就是初始化bean的属性值;如果属性是个bean,此处需要实例化依赖的bean,并缓存到一个叫earlySingletonObjects的map中;
5.initializeBean执行init或者post processors,动态代理也发生在这一步;
6.最终返回创建好的bean对象。
本篇文章就先分析到这里,循环依赖和动态代理的细节,在后续文章中继续分析。