public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {}
@Nullable
private BeanFactory parentBeanFactory;
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
@Nullable
private ClassLoader tempClassLoader;
private boolean cacheBeanMetadata = true;
@Nullable
private BeanExpressionResolver beanExpressionResolver;
@Nullable
private ConversionService conversionService;
private final Set propertyEditorRegistrars = new LinkedHashSet<>(4);
private final Map, Class extends PropertyEditor>> customEditors = new HashMap<>(4);
typeConverter
字段用于指定在Spring应用程序中处理类型转换的自定义 TypeConverter
。它允许您覆盖默认的 PropertyEditor
机制。PropertyEditor
来执行类型转换。但是,您可以提供自己的 TypeConverter
接口实现,并将其设置为 typeConverter
属性,以自定义类型转换过程。@Nullable
private TypeConverter typeConverter;
private final List embeddedValueResolvers = new CopyOnWriteArrayList<>();
private final List beanPostProcessors = new BeanPostProcessorCacheAwareList();
doGetBean()
方法来获取指定名称的 bean 对象。 doGetBean()
方法是 AbstractBeanFactory
中定义的一个抽象方法,需要具体的子类来实现。@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
doGetBean()
方法来获取指定名称和类型的 bean 对象。 doGetBean()
方法是 AbstractBeanFactory
中定义的一个抽象方法,需要具体的子类来实现。@Override
public T getBean(String name, Class requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
AbstractBeanFactory
类中 doGetBean()方法做了以下工作:
BeanCurrentlyInCreationException
异常,以避免循环引用。protected T doGetBean(
String name, @Nullable Class requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException {
String beanName = transformedBeanName(name);
Object beanInstance;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
beanInstance = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
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.
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 if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
StartupStep beanCreation = this.applicationStartup.start("spring.beans.instantiate")
.tag("beanName", name);
try {
if (requiredType != null) {
beanCreation.tag("beanType", requiredType::toString);
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
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 + "'");
}
registerDependentBean(dep, beanName);
try {
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
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;
}
});
beanInstance = 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);
}
beanInstance = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
}
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);
}
});
beanInstance = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
beanCreation.tag("exception", ex.getClass().toString());
beanCreation.tag("message", String.valueOf(ex.getMessage()));
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
finally {
beanCreation.end();
}
}
return adaptBeanInstance(name, beanInstance, requiredType);
}
AbstractBeanFactory
类中方法 adaptBeanInstance()做了以下工作:
BeanNotOfRequiredTypeException
异常。 T adaptBeanInstance(String name, Object bean, @Nullable Class> requiredType) {
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
Object convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return (T) convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
AbstractBeanFactory
类中的 containsBean()
方法做了以下工作:@Override
public boolean containsBean(String name) {
String beanName = transformedBeanName(name);
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found -> check parent.
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
AbstractBeanFactory
类中的 isSingleton()
方法的实现:&
开头)或 FactoryBean 自身是否是单例来判断返回结果;如果不是 FactoryBean,则根据是否是工厂引用来判断返回结果。@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
if (beanInstance instanceof FactoryBean) {
return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean>) beanInstance).isSingleton());
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isSingleton(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// In case of FactoryBean, return singleton status of created object if not a dereference.
if (mbd.isSingleton()) {
if (isFactoryBean(beanName, mbd)) {
if (BeanFactoryUtils.isFactoryDereference(name)) {
return true;
}
FactoryBean> factoryBean = (FactoryBean>) getBean(FACTORY_BEAN_PREFIX + beanName);
return factoryBean.isSingleton();
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
else {
return false;
}
}
AbstractBeanFactory
类中的 isPrototype()
方法的实现:&
开头),则根据 FactoryBean 的类型和 isSingleton() 方法来判断是否是原型对象。
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isPrototype(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isPrototype()) {
// In case of FactoryBean, return singleton status of created object if not a dereference.
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
}
// Singleton or scoped - not a prototype.
// However, FactoryBean may still produce a prototype object...
if (BeanFactoryUtils.isFactoryDereference(name)) {
return false;
}
if (isFactoryBean(beanName, mbd)) {
FactoryBean> fb = (FactoryBean>) getBean(FACTORY_BEAN_PREFIX + beanName);
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(
(PrivilegedAction) () ->
((fb instanceof SmartFactoryBean && ((SmartFactoryBean>) fb).isPrototype()) ||
!fb.isSingleton()),
getAccessControlContext());
}
else {
return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean>) fb).isPrototype()) ||
!fb.isSingleton());
}
}
else {
return false;
}
}
AbstractBeanFactory
类中的 isTypeMatch()
方法:name
参数获取对应的 bean 的名称,并进行相关的转换和处理。name
是否是以 &
开头的。FactoryBean
对象,则根据 isFactoryDereference
来判断是否与指定的 typeToMatch
匹配。如果单例 bean 不是 FactoryBean
,则通过直接比较类型来判断。如果类型匹配,则返回 true。BeanFactory
并且当前 BeanFactory
中不包含与指定的 name
对应的 bean 定义,则将匹配操作委托给父级 BeanFactory
。name
参数获取与其对应的合并后的 bean 定义信息和装饰 bean 定义信息。typeToMatch
的 isAssignableFrom()
方法判断是否匹配。若无法获取具体类型信息,则返回 false。/**
* Internal extended variant of {@link #isTypeMatch(String, ResolvableType)}
* to check whether the bean with the given name matches the specified type. Allow
* additional constraints to be applied to ensure that beans are not created early.
* @param name the name of the bean to query
* @param typeToMatch the type to match against (as a
* {@code ResolvableType})
* @return {@code true} if the bean type matches, {@code false} if it
* doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @since 5.2
* @see #getBean
* @see #getType
*/
protected boolean isTypeMatch(String name, ResolvableType typeToMatch, boolean allowFactoryBeanInit)
throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
boolean isFactoryDereference = BeanFactoryUtils.isFactoryDereference(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
if (beanInstance instanceof FactoryBean) {
if (!isFactoryDereference) {
Class> type = getTypeForFactoryBean((FactoryBean>) beanInstance);
return (type != null && typeToMatch.isAssignableFrom(type));
}
else {
return typeToMatch.isInstance(beanInstance);
}
}
else if (!isFactoryDereference) {
if (typeToMatch.isInstance(beanInstance)) {
// Direct match for exposed instance?
return true;
}
else if (typeToMatch.hasGenerics() && containsBeanDefinition(beanName)) {
// Generics potentially only match on the target class, not on the proxy...
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class> targetType = mbd.getTargetType();
if (targetType != null && targetType != ClassUtils.getUserClass(beanInstance)) {
// Check raw class match as well, making sure it's exposed on the proxy.
Class> classToMatch = typeToMatch.resolve();
if (classToMatch != null && !classToMatch.isInstance(beanInstance)) {
return false;
}
if (typeToMatch.isAssignableFrom(targetType)) {
return true;
}
}
ResolvableType resolvableType = mbd.targetType;
if (resolvableType == null) {
resolvableType = mbd.factoryMethodReturnType;
}
return (resolvableType != null && typeToMatch.isAssignableFrom(resolvableType));
}
}
return false;
}
else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
// null instance registered
return false;
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
}
// Retrieve corresponding bean definition.
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
// Setup the types that we want to match against
Class> classToMatch = typeToMatch.resolve();
if (classToMatch == null) {
classToMatch = FactoryBean.class;
}
Class>[] typesToMatch = (FactoryBean.class == classToMatch ?
new Class>[] {classToMatch} : new Class>[] {FactoryBean.class, classToMatch});
// Attempt to predict the bean type
Class> predictedType = null;
// We're looking for a regular reference but we're a factory bean that has
// a decorated bean definition. The target bean should be the same type
// as FactoryBean would ultimately return.
if (!isFactoryDereference && dbd != null && isFactoryBean(beanName, mbd)) {
// We should only attempt if the user explicitly set lazy-init to true
// and we know the merged bean definition is for a factory bean.
if (!mbd.isLazyInit() || allowFactoryBeanInit) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class> targetType = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
if (targetType != null && !FactoryBean.class.isAssignableFrom(targetType)) {
predictedType = targetType;
}
}
}
// If we couldn't use the target type, try regular prediction.
if (predictedType == null) {
predictedType = predictBeanType(beanName, mbd, typesToMatch);
if (predictedType == null) {
return false;
}
}
// Attempt to get the actual ResolvableType for the bean.
ResolvableType beanType = null;
// If it's a FactoryBean, we want to look at what it creates, not the factory class.
if (FactoryBean.class.isAssignableFrom(predictedType)) {
if (beanInstance == null && !isFactoryDereference) {
beanType = getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit);
predictedType = beanType.resolve();
if (predictedType == null) {
return false;
}
}
}
else if (isFactoryDereference) {
// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
// type but we nevertheless are being asked to dereference a FactoryBean...
// Let's check the original bean class and proceed with it if it is a FactoryBean.
predictedType = predictBeanType(beanName, mbd, FactoryBean.class);
if (predictedType == null || !FactoryBean.class.isAssignableFrom(predictedType)) {
return false;
}
}
// We don't have an exact type but if bean definition target type or the factory
// method return type matches the predicted type then we can use that.
if (beanType == null) {
ResolvableType definedType = mbd.targetType;
if (definedType == null) {
definedType = mbd.factoryMethodReturnType;
}
if (definedType != null && definedType.resolve() == predictedType) {
beanType = definedType;
}
}
// If we have a bean type use it so that generics are considered
if (beanType != null) {
return typeToMatch.isAssignableFrom(beanType);
}
// If we don't have a bean type, fallback to the predicted type
return typeToMatch.isAssignableFrom(predictedType);
}
AbstractBeanFactory
类中的 getType(String name, boolean allowFactoryBeanInit)
方法的具体实现:name
参数进行转换处理,得到对应的 bean 名称 beanName
。NullBean
,则执行以下判断:
FactoryBean
类型,且不是工厂引用,则返回通过调用 getTypeForFactoryBean()
方法获取的 bean 类型。BeanFactory
并且当前 BeanFactory
中不包含与 beanName
参数对应的 bean 定义。
BeanFactory
的 getType()
方法获取 bean 类型。mbd
。dbd
,如果存在且不是工厂引用,则预测装饰的 bean 的类型 targetClass
。
predictBeanType()
方法预测 bean 类型,并将结果赋值给 beanClass
变量。beanClass
是否是 FactoryBean 类型的子类,如果是,则根据是否为工厂引用来判断返回 bean 类型还是 FactoryBean 类型。
getTypeForFactoryBean()
方法获取 FactoryBean 创建的对象类型。beanClass
,表示返回的是 FactoryBean 类型。@Override
@Nullable
public Class> getType(String name, boolean allowFactoryBeanInit) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null && beanInstance.getClass() != NullBean.class) {
if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
return getTypeForFactoryBean((FactoryBean>) beanInstance);
}
else {
return beanInstance.getClass();
}
}
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.getType(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class> targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return targetClass;
}
}
Class> beanClass = predictBeanType(beanName, mbd);
// Check bean class whether we're dealing with a FactoryBean.
if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
return getTypeForFactoryBean(beanName, mbd, allowFactoryBeanInit).resolve();
}
else {
return beanClass;
}
}
else {
return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
}
}
AbstractBeanFactory
类中的 getTypeConverter()
方法的具体实现: customConverter
。SimpleTypeConverter
。ConversionService
,通过调用 getConversionService()
方法获取转换服务。registerCustomEditors()
方法实现。typeConverter
。
@Override
public TypeConverter getTypeConverter() {
TypeConverter customConverter = getCustomTypeConverter();
if (customConverter != null) {
return customConverter;
}
else {
// Build default TypeConverter, registering custom editors.
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
typeConverter.setConversionService(getConversionService());
registerCustomEditors(typeConverter);
return typeConverter;
}
}
AbstractBeanFactory
类中的 resolveEmbeddedValue(String value)
方法的具体实现:value
参数是否为 null,如果为 null,则直接返回 null。value
赋值给 result
变量,用于存储解析后的结果。embeddedValueResolvers
中的每个解析器 resolver
,依次对 result
进行解析。resolver
,调用它的 resolveStringValue()
方法对 result
进行解析,得到新的解析结果并赋值给 result
。result
为 null,则直接返回 null。result
。@Override
@Nullable
public String resolveEmbeddedValue(@Nullable String value) {
if (value == null) {
return null;
}
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
if (result == null) {
return null;
}
}
return result;
}
AbstractBeanFactory
类中的 getBeanPostProcessorCache()
方法的具体实现:bpCache
。bpCache
为 null,则说明缓存为空,需要重新构建。BeanPostProcessorCache
。beanPostProcessors
中的每个后置处理器 bp
。InstantiationAwareBeanPostProcessor
接口的后置处理器 bp
,将其添加到缓存的 instantiationAware
列表中,并判断是否还实现了 SmartInstantiationAwareBeanPostProcessor
接口,如果是,则将其也添加到缓存的 smartInstantiationAware
列表中。DestructionAwareBeanPostProcessor
接口的后置处理器 bp
,将其添加到缓存的 destructionAware
列表中。MergedBeanDefinitionPostProcessor
接口的后置处理器 bp
,将其添加到缓存的 mergedDefinition
列表中。this.beanPostProcessorCache
。bpCache
。BeanPostProcessorCache getBeanPostProcessorCache() {
BeanPostProcessorCache bpCache = this.beanPostProcessorCache;
if (bpCache == null) {
bpCache = new BeanPostProcessorCache();
for (BeanPostProcessor bp : this.beanPostProcessors) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
bpCache.instantiationAware.add((InstantiationAwareBeanPostProcessor) bp);
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
bpCache.smartInstantiationAware.add((SmartInstantiationAwareBeanPostProcessor) bp);
}
}
if (bp instanceof DestructionAwareBeanPostProcessor) {
bpCache.destructionAware.add((DestructionAwareBeanPostProcessor) bp);
}
if (bp instanceof MergedBeanDefinitionPostProcessor) {
bpCache.mergedDefinition.add((MergedBeanDefinitionPostProcessor) bp);
}
}
this.beanPostProcessorCache = bpCache;
}
return bpCache;
}
AbstractBeanFactory
类中的 isFactoryBean(String name)
方法的具体实现:isFactoryBean(String name)
方法。isFactoryBean(String beanName, RootBeanDefinition bd)
方法来进行判断。isFactoryBean(String beanName, RootBeanDefinition bd)
方法中,会根据合并后的 bean 定义来判断是否是 FactoryBean 的实现。如果合并后的 bean 定义指定了 factoryBeanName
属性,则表明该 bean 定义是 FactoryBean 的实现,返回 true;否则,返回 false。@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
return (beanInstance instanceof FactoryBean);
}
// No singleton instance found -> check bean definition.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
// No bean definition found in this factory -> delegate to parent.
return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
}
return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
AbstractBeanFactory
类中的 destroyBean(String beanName, Object bean, RootBeanDefinition mbd)
方法的具体实现:首先,通过 DisposableBeanAdapter
类来包装 bean 实例,并提供必要的信息,如 bean 名称、合并的 bean 定义、后置处理器缓存等。
创建 DisposableBeanAdapter
对象时,会传入相应的参数,如 bean 实例、bean 名称、合并的 bean 定义、销毁感知的标志以及访问控制上下文。
最后,调用 DisposableBeanAdapter
的 destroy()
方法来执行销毁逻辑。DisposableBeanAdapter
会首先调用所有 DestructionAwareBeanPostProcessor
的 postProcessBeforeDestruction()
方法对 bean 进行预处理,然后再调用 bean 自身实现 DisposableBean
接口的 destroy()
方法进行销毁。
在销毁过程中,可以触发各种清理操作,如资源释放、销毁相关的对象等。
在默认情况下,Spring 容器并不会自动销毁作用域为单例的 bean 实例,而仅对作用域为原型的 bean 实例执行销毁操作。当容器关闭时,会触发单例 bean 的销毁。如果需要显式销毁单例 bean,可以通过配置 destroy-method
或实现 DisposableBean
接口来实现。
protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, getAccessControlContext()).destroy();
}
AbstractBeanFactory
类中的 createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
方法的抽象声明:该方法用于根据给定的合并的 bean 定义(和参数)创建一个 bean 实例。如果是子定义,则 bean 定义已经与父定义合并。 在实际创建 bean 时,所有的 bean 检索方法都会委托给这个方法。
具体的实现逻辑由具体的 bean 工厂实现类负责实现。
/**
* Create a bean instance for the given merged bean definition (and arguments).
* The bean definition will already have been merged with the parent definition
* in case of a child definition.
* All bean retrieval methods delegate to this method for actual bean creation.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
*/
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;