Spring Bean的实例化
Bean的实例化顾名思义就是创建bean,然后被spring ioc容器纳入管理,然后在应用范围内可以获取bean,
在前面的章节中介绍了BeanDefinition的加载与注册,那么bean的实例化步骤是建立在BeanDefinition的加载与注册之上,
Bean的实例化包括创建所需的bean实例以及根据需要同时实例化bean所依赖的bean实例。
还记得在介绍beanFactory核心组件时有介绍BeanFactory的getBean方法
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
该方法就是根据配置的bean的name以及bean的Class类型获取所需的bean对象,该方法就是我们探讨bean实例化的入口
BeanFactory实例化bean的时序图如下:
AbstractBeanFactory.java
protected <T> T doGetBean( final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException { final String beanName = transformedBeanName(name); Object bean; // 直接尝试从缓存中获取或者singletonFactories中的ObjectFactory中获取 // 为什么会有这段代码,因为在创建单例bean的时候会存在依赖注入的情况,而在创建依赖时为了避免循环依赖 // spring创建bean的原则是不等bean创建完成就会将创建bean的ObjectFactory提早曝光,也就是将ObjectFactory加入到缓存中,一旦下一个bean创建的时候需要依赖上一个bean则直接使用ObjectFactory 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 = getObjectForBeanInstance(sharedInstance, name, beanName, null); } else { // 判断当前的bean当前是否处于创建状态*(在当前线程中),避免重复创建,一般用于解决循环依赖 // 只有在单例的情况下才会尝试解决循环依赖,原型模式下,如果存在 A,B互相依赖的时候,就会产生A还未创建完成的时候,因为对B的创建再次返回创建A,造成循环依赖,这是不允许的 if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName); } // 检查当前的beanfactory是否存在父beanfactory 若存在则从父beanfactory获取实例 BeanFactory parentBeanFactory = getParentBeanFactory(); if (parentBeanFactory != null && !containsBeanDefinition(beanName)) { // Not found -> check parent. String nameToLookup = originalBeanName(name); 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); } } // 将指定的bean标记为已创建(或即将创建)。允许bean工厂优化其缓存以重复创建指定的bean if (!typeCheckOnly) { markBeanAsCreated(beanName); } try { //将GenericBeanDefinition合并为RootBeanDefinition final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName); //检查RootBeanDefinition是否是抽象的,如果是抽象将无法实例化 checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on. String[] dependsOn = mbd.getDependsOn(); //确保当前bean所依赖的bean的先被初始化 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 + "'"); } //为给定的bean注册一个依赖bean,在销毁给定的bean之前销毁 registerDependentBean(dep, beanName); try { //获取并实例化依赖的bean getBean(dep); } catch (NoSuchBeanDefinitionException ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "'" + beanName + "' depends on missing bean '" + dep + "'", ex); } } } // 创建bean的实例对象. // 如果bean的scope为"singleton"或者为""(也就是未指定scope的时候)创建单实例的bean if (mbd.isSingleton()) { //获取并创建单例对象 sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { try { 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实例的对象,如果是FactoryBean,要么是bean实例本身,要么是它创建的对象 // 因为在这一步的时候只是获得bean的最原始状态,并不一定是用户最终需要的bean,为什么呢,这里会考虑factoryBean,如果得到的bean是一个factoryBean // 则会最终调用factoryBean的getObject获得最终的bean bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd); } //创建Prototype作用域的bean 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); } //创建Prototype作用域的bean 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, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { 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; } } // 检查所需类型是否与实际bean实例的类型匹配. if (requiredType != null && bean != null && !requiredType.isInstance(bean)) { try { return getTypeConverter().convertIfNecessary(bean, requiredType); } catch (TypeMismatchException ex) { if (logger.isDebugEnabled()) { logger.debug("Failed to convert bean '" + name + "' to required type '" + ClassUtils.getQualifiedName(requiredType) + "'", ex); } throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass()); } } //返回所需要的bean return (T) bean; }
单例bean的创建
DefaultSingletonBeanRegistry.java
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
//获取缓存的单例bean
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 + "'");
}
//单例创建之前的回调。默认实现将singleton注册为当前正在创建的
beforeSingletonCreation(beanName);
//新创建单例的标识
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
//通过单例工厂创建bean
singletonObject = singletonFactory.getObject();
//将新创建单例的标识设为true
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;
}
//单例创建后的回调。默认实现将singleton标记为不在创建中
afterSingletonCreation(beanName);
}
if (newSingleton) {
//将给定的单例对象添加到此工厂的单例缓存中。
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
单例对象的创建是通过ObjectFactory对象工厂来创建的,这是一个接口
T getObject() throws BeansException;
所以在AbstractBeanFactory.java中标红部分有一个ObjectFactory的匿名内部类的实现
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
destroySingleton(beanName);
throw ex;
}
}
});
该匿名内部类创建对象的行为实际则调用了createBean(beanName, mbd, args);方法,此方法在AbstractBeanFactory中是一个抽象方法,具体实现是在AbstractAutowireCapableBeanFactory中
AbstractAutowireCapableBeanFactory.java
protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// 确保此时bean类实际上已经解析,并从Beandefinition中取得解析的Class对象.
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 {
// 让beanpostprocessor有机会返回代理而不是目标bean实例.
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);
}
// 根据BeanDefinition创建bean实例
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) throws BeanCreationException { // bean实例的包装类. BeanWrapper instanceWrapper = null; if (mbd.isSingleton()) { instanceWrapper = this.factoryBeanInstanceCache.remove(beanName); } if (instanceWrapper == null) { //创建bean的实例 instanceWrapper = createBeanInstance(beanName, mbd, args); } //获取bean的接口 final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null); //获取bean的类型 Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null); //定义要实例化的目标类型 mbd.resolvedTargetType = beanType; // 允许后处理(post-processors)程序修改合并的bean定义 synchronized (mbd.postProcessingLock) { if (!mbd.postProcessed) { try { applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName); } catch (Throwable ex) { throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", ex); } mbd.postProcessed = true; } } //创建bean的时候,用来解决循环依赖,A -> b ,B->A // 每个单例对象在创建的时候首先会加入到正在创建缓存中singletonsCurrentlyInCreation中 // 并且会在bean的属性填充之前 暴露一个ObjectFactory到singletonFactories<beanName,ObjectFactory> // 当检测到时循环引用的时候会通过之前暴露的ObjectFactory获取前期实例化好的并且是依赖的bean 进行注入 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, new ObjectFactory<Object>() { @Override public Object getObject() throws BeansException { return getEarlyBeanReference(beanName, mbd, bean); } }); } // 初始化bean的实例 // 并定义一个向外暴露的bean. Object exposedObject = bean; try { //填充bean的属性以及属性依赖的对象,依赖的属性对象将会通过getBean(name同样的逻辑)实例化,然后将依赖的对象填充到当前的bean的属性中 populateBean(beanName, mbd, instanceWrapper); if (exposedObject != null) { 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) { //通过之前暴露的singletonFactories<beanName,ObjectFactory> 跟据beanName获取对应的ObjectFactory // 通过ObjectFactory获取早期依赖的对象 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<String>(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."); } } } } // 将bean注册为一次性的. try { registerDisposableBeanIfNecessary(beanName, bean, mbd); } catch (BeanDefinitionValidationException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex); } return exposedObject; }
createBeanInstance的逻辑,并返回bean的包装类BeanWrapper
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
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());
}
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
// Need to determine the constructor...
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// 无需特殊处理:只需使用无参数构造函数反射实例化bean对象
return instantiateBean(beanName, mbd);
}
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
@Override
public Object run() {
return getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
}, getAccessControlContext());
}
else {
//获取实例化策略,来对原生的bean进行实例化,最终会调用SimpleInstantiationStrategy的instantiate方法
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
//将原始bean的实例对象包装成BeanWrapperImpl实例
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
//对包装类进行初始化
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
SimpleInstantiationStrategy.java
public Object instantiate(RootBeanDefinition bd, String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
if (bd.getMethodOverrides().isEmpty()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(new PrivilegedExceptionAction<Constructor<?>>() {
@Override
public Constructor<?> run() throws Exception {
return clazz.getDeclaredConstructor((Class[]) null);
}
});
}
else {
//反射获取bean的无参数构造器
constructorToUse = clazz.getDeclaredConstructor((Class[]) null);
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}
BeanUtils.java
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException {
Assert.notNull(ctor, "Constructor must not be null");
try {
反射创建bean的实例
ReflectionUtils.makeAccessible(ctor);
return ctor.newInstance(args);
}
catch (InstantiationException ex) {
throw new BeanInstantiationException(ctor, "Is it an abstract class?", ex);
}
catch (IllegalAccessException ex) {
throw new BeanInstantiationException(ctor, "Is the constructor accessible?", ex);
}
catch (IllegalArgumentException ex) {
throw new BeanInstantiationException(ctor, "Illegal arguments for constructor", ex);
}
catch (InvocationTargetException ex) {
throw new BeanInstantiationException(ctor, "Constructor threw exception", ex.getTargetException());
}
}
bean的填充逻辑
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
PropertyValues pvs = mbd.getPropertyValues();
if (bw == null) {
if (!pvs.isEmpty()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
return;
}
}
//让任何instantiationawarebeanpostprocessor有机会在设置属性之前修改bean的状态。
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
if (!continueWithPropertyPopulation) {
return;
}
//如果bean配置了自动装配 byName或ByType则进行自动装配属性
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
//申请并设置bean的属性值
applyPropertyValues(beanName, mbd, bw, pvs);
}
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) { //如果bean没有任何属性值则填充结束 if (pvs == null || pvs.isEmpty()) { return; } if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) { ((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext()); } MutablePropertyValues mpvs = null; List<PropertyValue> original; if (pvs instanceof MutablePropertyValues) { mpvs = (MutablePropertyValues) pvs; if (mpvs.isConverted()) { // Shortcut: use the pre-converted values as-is. try { bw.setPropertyValues(mpvs); return; } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } } original = mpvs.getPropertyValueList(); } else { original = Arrays.asList(pvs.getPropertyValues()); } TypeConverter converter = getCustomTypeConverter(); if (converter == null) { converter = bw; } BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter); // Create a deep copy, resolving any references for values. List<PropertyValue> deepCopy = new ArrayList<PropertyValue>(original.size()); boolean resolveNecessary = false; for (PropertyValue pv : original) { if (pv.isConverted()) { deepCopy.add(pv); } else { //提取属性名 String propertyName = pv.getName(); //属性值对象 Object originalValue = pv.getValue(); //在必要时解析对工厂中其他bean的任何引用。 Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue); Object convertedValue = resolvedValue; boolean convertible = bw.isWritableProperty(propertyName) && !PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName); if (convertible) { //转换在配置文件中的各种属性值到map、list、properties的转换,并将转换后的值填充到bean的属性当中 convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter); } //可能在合并的bean定义中存储转换后的值,以避免对每个创建的bean实例进行重新转换. if (resolvedValue == originalValue) { if (convertible) { pv.setConvertedValue(convertedValue); } deepCopy.add(pv); } else if (convertible && originalValue instanceof TypedStringValue && !((TypedStringValue) originalValue).isDynamic() && !(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) { pv.setConvertedValue(convertedValue); deepCopy.add(pv); } else { resolveNecessary = true; deepCopy.add(new PropertyValue(pv, convertedValue)); } } } if (mpvs != null && !resolveNecessary) { mpvs.setConverted(); } // Set our (possibly massaged) deep copy. try { bw.setPropertyValues(new MutablePropertyValues(deepCopy)); } catch (BeansException ex) { throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Error setting property values", ex); } }
BeanDefinitionValueResolver.java
public Object resolveValueIfNecessary(Object argName, Object value) {
//如果依赖的属性是一个运行时的引用,则解析引用类型
if (value instanceof RuntimeBeanReference) {
RuntimeBeanReference ref = (RuntimeBeanReference) value;
return resolveReference(argName, ref);
}
else if (value instanceof RuntimeBeanNameReference) {
String refName = ((RuntimeBeanNameReference) value).getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (!this.beanFactory.containsBean(refName)) {
throw new BeanDefinitionStoreException(
"Invalid bean name '" + refName + "' in bean reference for " + argName);
}
return refName;
}
}
private Object resolveReference(Object argName, RuntimeBeanReference ref) {
try {
String refName = ref.getBeanName();
refName = String.valueOf(doEvaluate(refName));
if (ref.isToParent()) {
if (this.beanFactory.getParentBeanFactory() == null) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Can't resolve reference to bean '" + refName +
"' in parent factory: no parent factory available");
}
return this.beanFactory.getParentBeanFactory().getBean(refName);
}
else {
//如果依赖的属性是一个引用,则根据引用的属性名称创建依赖的bean并注册依赖的bean
Object bean = this.beanFactory.getBean(refName);
this.beanFactory.registerDependentBean(refName, this.beanName);
return bean;
}
}
catch (BeansException ex) {
throw new BeanCreationException(
this.beanDefinition.getResourceDescription(), this.beanName,
"Cannot resolve reference to bean '" + ref.getBeanName() + "' while setting " + argName, ex);
}
}
Bean的循环依赖解决方式
循环依赖解决方式的原则
1: 如果bean的依赖是通过构造器注入,则拒绝解决
其原理如下:
原型模式下,如果存在 ServiceA -> ServiceB,ServiceB -> ServiceA互相依赖的时候,在创建ServiceA的时候首先会将ServiceA添加到Set<String> singletonsCurrentlyInCreation中,检测到依赖ServiceB然后实例化ServiceB
并将ServiceB添加到Set<String> singletonsCurrentlyInCreation,同时检测到依赖的ServiceA,然后再一次实例化ServiceA,当检测到ServiceA已经存在singletonsCurrentlyInCreation之中,则会抛出异常BeanCurrentlyInCreationException
根据异常栈信息可以看到如下信息:
Error creating bean with name 'ServiceB': Requested bean is currently in creation: Is there an unresolvable circular reference?
翻译: 创建名为'ServiceB'的bean时出错:请求的bean(ServiceA)当前正在创建中:是否存在无法解析的循环引用?
具体代码在DefaultSingletonBeanRegistry.java中
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
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 + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
......
}
protected void beforeSingletonCreation(String beanName) {
if (!this.inCreationCheckExclusions.contains(beanName) && !this.singletonsCurrentlyInCreation.add(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
}
2 : 如果bean的依赖是通过Setter注入,则解决方式如下:
第一步:
首先获取ServiceA的时候从singletonObjects或者earlySingletonObjects或者singletonFactories中的ObjectFactory获取单例
由于第一步,singletonObjects中没有ServiceA的缓存,当前的singletonsCurrentlyInCreation还没有该ServiceA,故不满足条件
protected Object getSingleton(String beanName, boolean allowEarlyReference) { //从bean工厂的单例缓存中获取 Object singletonObject = this.singletonObjects.get(beanName); //如果缓存没有的时候再判断当前的bean是否处在创建之中 if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) { synchronized (this.singletonObjects) { //从earlySingletonObjects缓存中获取ObjectFactory singletonObject = this.earlySingletonObjects.get(beanName); if (singletonObject == null && allowEarlyReference) { //从bean对应的ObjectFactory缓存中获取ObjectFactory ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName); if (singletonFactory != null) { //从ObjectFactory中获取 singletonObject = singletonFactory.getObject(); this.earlySingletonObjects.put(beanName, singletonObject); this.singletonFactories.remove(beanName); } } } } return (singletonObject != NULL_OBJECT ? singletonObject : null); }
第二步:
实例化ServiceA,在实例化之前同样需要执行beforeSingletonCreation(beanName)逻辑,将ServiceA放在当前创建缓存中singletonsCurrentlyInCreation
然后实例化ServiceA,调用无参数的构造器获得原始的ServiceA的实例,然后将ServiceA添加到singletonFactories
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
.....
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
addSingletonFactory(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}
return exposedObject;
}
第三步骤:
填充ServiceA,发现有一个RuntimeBeanReference的引用ServiceB,然后解析引用ServiceB,然后执行getBean("serviceB"),这一步有走到了实例化ServiceB的逻辑
由于ServiceB也是首次实例化,执行的逻辑与ServiceA相同,将ServiceB置于singletonsCurrentlyInCreation之中,同时将实例化ServiceB,调用无参数的构造器获得原始的ServiceB的实例,然后将ServiceB添加到singletonFactories
再继续执行,发现有一个RuntimeBeanReference的引用ServiceA的引用,然后又执行getBean("serviceA"),的逻辑,这一次又会走到protected Object getSingleton(String beanName, boolean allowEarlyReference)方法
只不过走到这一步的时候与第一次实例化ServiceA不同,已经发生了微妙的变化,由于最开始的时候ServiceA的实例已经过构造器反射实例化,同时最开始的时候singletonsCurrentlyInCreation已经包含ServiceA,同时singletonFactories中也包含了ServiceA的ObjectFactory
所以这一步将直接根据ServiceA的ObjectFactory暴露出ServiceA实例,然后将ServiceA注入到ServiceB
第四步:
由第三步可知,serviceB的实例已经初始成功,那么最后ServiceA再回到装配ServiceB的时候 ,同样ServiceB也已经处于singletonsCurrentlyInCreation,且singletonFactories中也包含了ServiceB的ObjectFactoryB
那么装配ServiceA的逻辑也是如此
附录:
构造器的循环依赖并不能像解决Setter那样,因为构造器注入的时候,在反射创建原对象时,发现构造器参数有依赖的bean,于是通过ConstructorResolver解析器解析构造其参数RuntimeBeanReference ,然后通过new BeanDefinitionValueResolver,
发现依赖直接通过 getBean("referenceName")立刻实例化依赖的对象,并不能像setter那样,调用无参数的构造器实例化
然后提前暴露一个ObjectFactory到singletonFactories中,所以当发现依赖的对象处于singletonsCurrentlyInCreation中时,抛出异常