Spring源码之路-DefaulListableBeanFactory
总结
此抽象工厂继承了FactoryBeanRegistrySupport,然后实现了ConfigurableBeanFactory接口。此类主要实现的是ConfigurableBeanFactory接口
此类中有关键的方法getBean()
方法,有几个重载的方法,但最终都会调用到doGetBean()
方法中,这里就是从容器中获取Bean的关键方法。
将给定的Bean的名称转换成实际的Bean名称
去DefaultSingletonBeanRegistry
中看是否有此Bean对象的缓存,
如果有则获取缓存的Bean对象,然后调用AbstractBeanFactory.getObjectForBeanInstance()
方法,将缓存的Bean对象转换成具体的Bean实例。(这里要转换是因为这个Bean有可能是FactoryBean,如果是FactoryBean,那么根据你上送的Bean的名称来决定你是要获取FactoryBean这个对象,还是要获取由FactoryBean对象所创建的对象。如果是以 &
开头则是获取FactoryBean这个对象,否则是获取缓存的Bean对象本身或者是由FactoryBean对象所生成的对象)
如果没有,则判断需要获取这个Bean的名称是否在当前线程中是一个正在创建的Prototype类型的Bean对象。如果是直接抛出异常。(这个地方是解决Prototype类型Bean对象,在出现循环依赖的处理方法,因为都都是Prototype类型的,当产生循环依赖的时候,Spring容器无法帮我们解决,所以就会直接抛出异常)
获取父的BeanFactory,如果有BeanFactory并且在当前子的BeanFactory中没有对应的BeanDefinition,则将对Bean的获取转交给父BeanFactory的getBean()方法
获取本地合并后的BeanDefinition,如果获取不到则会抛出异常
根据获取到的BeanDefinition来获取依赖的Bean的名称,将依赖与被依赖的关系保存起来,然后通过调用getBean方法依次获取依赖的Bean实例。
根据BeanDefinition来判断当前要创建的Bean是否是单例的,如果是单例的,则调用的DefaultSingletonBeanRegistry.getSingleton(String beanName, ObjectFactory> singletonFactory)
方法来进行获取,这个在【6.Spring源码之路-DefaulListableBeanFactory - DefaultSingletonBeanRegistry】
中有介绍。
如果当前是Prototype类型的,那么会先将要创建的Bean的名称添加到当前的线程变量中去,然后调用createBean(String beanName, RootBeanDefinition mbd, Object[] args)
去创建,创建完成后,将Bean的名称从当先的线程变量中删除
如果不是单例也不是Prototype类型,那么就是自定义作用于的,获取作用域标识,如果作用域标识为空,则抛出异常。然后通过调用Scope.get(String name, ObjectFactory> objectFactory)
方法来获取对应作用域的对象,此作用域的对象创建的时候,也会将Bean的名称添加到当前的线程变量中去,创建完成后,将Bean的名称从当先的线程变量中删除
所有的Bean在获取到Bean实例之后都会调用AbstractBeanFactory.getObjectForBeanInstance()
方法。【在1. 里面有注释说明】
判断创建出来Bean对象的类型和需要的类型是否一致,如果不一致,则使用ConverService进行转换,如果不能转换成需要的类型,则抛出异常。
上面的Bean的创建过程最终都会调用createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
这个方法来进行Bean的创建,这个方法在当前类中是抽象的,具体的实现是由子类来进行的。
源码注释的大概翻译
/**
* {@link org.springframework.beans.factory.BeanFactory}实现的抽象基类,
* 提供了{@link org.springframework.beans.factory.config.ConfigurableBeanFactory}
* SPI的全部功能。
* 假定有一个可列出的bean工厂:因此也可以用作bean工厂实现的基类,该工厂从某
* 些后端资源(其中bean定义访问是一项昂贵的操作)中获取bean定义的实现。
*
* 此类通过其基类提供一个单例缓存(通过其基类
* {@link org.springframework.beans.factory.support.DefaultSingletonBeanRegistry},
* 单例/原型确定,{@ link org.springframework.beans.factory. FactoryBean}
* 处理,别名,用于子bean定义的bean定义合并,和bean销毁接口,自定义销毁方法)
* 此外,它还可以管理bean工厂,通过实现
* {@link org.springframework.beans.factory.HierarchicalBeanFactory}接口实现层次结
* 构(在未知bean的情况下委托给父对象)
* 要由子类实现的主要模板方法是{ @link #getBeanDefinition}和{@link #createBean},
* 分别为给定的bean名称检索一个beanDefinition和为给定的bean定义创建一个bean实例
* 这些操作的默认实现在{@link DefaultListableBeanFactory} 和
* {@link AbstractAutowireCapableBeanFactory}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Costin Leau
* @author Chris Beams
* @author Phillip Webb
* @since 15 April 2001
* @see #getBeanDefinition
* @see #createBean
* @see AbstractAutowireCapableBeanFactory#createBean
* @see DefaultListableBeanFactory#getBeanDefinition
*/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
/** 父bean工厂,用于bean继承支持。 */
@Nullable
private BeanFactory parentBeanFactory;
/** 必要时使用ClassLoader解析Bean类名称. */
@Nullable
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/** 如有必要,ClassLoader可以临时解析Bean类名称. */
@Nullable
private ClassLoader tempClassLoader;
/** 是否缓存Bean元数据还是在每次访问时重新获取它. */
private boolean cacheBeanMetadata = true;
/** BeanDefinition值中表达式的解析策略 */
@Nullable
private BeanExpressionResolver beanExpressionResolver;
/** 使用Spring ConversionService来代替PropertyEditors. */
@Nullable
private ConversionService conversionService;
/** 自定义PropertyEditorRegistrars来应用于这个工厂的bean. */
private final Set propertyEditorRegistrars = new LinkedHashSet<>(4);
/** 自定义属性定义程序应用于此工厂的bean. */
private final Map, Class extends PropertyEditor>> customEditors = new HashMap<>(4);
/** 要使用的自定义类型转换器,覆盖默认的PropertyEditor机制. */
@Nullable
private TypeConverter typeConverter;
/** 用于带有占位符的属性值的字符串解析器. */
private final List embeddedValueResolvers = new CopyOnWriteArrayList<>();
/**申请 BeanPostProcessors. */
private final List beanPostProcessors = new BeanPostProcessorCacheAwareList();
/** 预先过滤的后置处理器的缓存。 */
@Nullable
private volatile BeanPostProcessorCache beanPostProcessorCache;
/** 从Scope标识符字符串映射到相应的Scope. */
private final Map scopes = new LinkedHashMap<>(8);
/** 与SecurityManager一起运行时使用的安全上下文. */
@Nullable
private SecurityContextProvider securityContextProvider;
/** 从bean名称映射到合并的RootBeanDefinition. */
private final Map mergedBeanDefinitions = new ConcurrentHashMap<>(256);
/** 至少已经创建过一次的bean的名称. */
private final Set alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<>(256));
/** 当前正在创建的bean的名称. */
private final ThreadLocal prototypesCurrentlyInCreation =
new NamedThreadLocal<>("Prototype beans currently in creation");
/**
* Create a new AbstractBeanFactory.
*/
public AbstractBeanFactory() {
}
/**
* 使用给定的父元素创建一个新的AbstractBeanFactory.
* @param parentBeanFactory 父bean工厂,或{@code null},如果没有
* @see #getBean
*/
public AbstractBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this.parentBeanFactory = parentBeanFactory;
}
//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//---------------------------------------------------------------------
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public T getBean(String name, Class 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);
}
/**
* 返回指定bean的实例,该实例可以是共享的,也可以是独立的。.
* @param name 要检索的bean的名称
* @param requiredType 需要检索的bean类型
* @param args 使用显式参数创建bean实例时使用的参数
* (仅在创建新实例而不是检索现有实例时应用)
* @return 返回bean的实例
* @throws BeansException 如果bean不能被创建
*/
public T getBean(String name, @Nullable Class requiredType, @Nullable Object... args)
throws BeansException {
return doGetBean(name, requiredType, args, false);
}
/**
* 返回指定bean的实例,该实例可以是共享的,也可以是独立的。
* @param name 要检索的bean的名称
* @param requiredType 需要检索的bean类型
* @param args 使用显式参数创建bean实例时使用的参数
* (仅在创建新实例而不是检索现有实例时应用)
* @param typeCheckOnly 是否为类型检查获取实例,非实际使用
* @return 返回bean的实例
* @throws BeansException 如果bean不能被创建
*/
@SuppressWarnings("unchecked")
protected T doGetBean(final String name, @Nullable final Class requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// 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 + "'");
}
}
bean = 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);
}
try {
final 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;
}
});
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();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
}
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 ScopeNotActiveException(beanName, scopeName, ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return 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;
}
@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)));
}
@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;
}
}
@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)) {
final 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;
}
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, typeToMatch, true);
}
/**
* {@link #isTypeMatch(String,ResolvableType)} 的内部扩展变体,
* 用于检查具有给定名称的bean是否与指定的类型匹配。允许应用附加约束,
* 以确保不及早创建bean。
* @param name 要查询的bean的名称
* @param typeToMatch 要匹配的类型(作为{@code ResolvableType})
* @return {@code true}如果bean类型匹配,{@ code false}如果它不匹配或尚未确定
* doesn't match or cannot be determined yet
* @throws NoSuchBeanDefinitionException 如果没有给定名称的bean
* @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);
}
@Override
public boolean isTypeMatch(String name, Class> typeToMatch) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch));
}
@Override
@Nullable
public Class> getType(String name) throws NoSuchBeanDefinitionException {
return getType(name, true);
}
@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);
}
}
@Override
public String[] getAliases(String name) {
String beanName = transformedBeanName(name);
List aliases = new ArrayList<>();
boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
String fullBeanName = beanName;
if (factoryPrefix) {
fullBeanName = FACTORY_BEAN_PREFIX + beanName;
}
if (!fullBeanName.equals(name)) {
aliases.add(fullBeanName);
}
String[] retrievedAliases = super.getAliases(beanName);
String prefix = factoryPrefix ? FACTORY_BEAN_PREFIX : "";
for (String retrievedAlias : retrievedAliases) {
String alias = prefix + retrievedAlias;
if (!alias.equals(name)) {
aliases.add(alias);
}
}
if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null) {
aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
}
}
return StringUtils.toStringArray(aliases);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
@Nullable
public BeanFactory getParentBeanFactory() {
return this.parentBeanFactory;
}
@Override
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
//---------------------------------------------------------------------
// Implementation of ConfigurableBeanFactory interface
//---------------------------------------------------------------------
@Override
public void setParentBeanFactory(@Nullable BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
if (this == parentBeanFactory) {
throw new IllegalStateException("Cannot set parent bean factory to self");
}
this.parentBeanFactory = parentBeanFactory;
}
@Override
public void setBeanClassLoader(@Nullable ClassLoader beanClassLoader) {
this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
}
@Override
@Nullable
public ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
@Override
public void setTempClassLoader(@Nullable ClassLoader tempClassLoader) {
this.tempClassLoader = tempClassLoader;
}
@Override
@Nullable
public ClassLoader getTempClassLoader() {
return this.tempClassLoader;
}
@Override
public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
this.cacheBeanMetadata = cacheBeanMetadata;
}
@Override
public boolean isCacheBeanMetadata() {
return this.cacheBeanMetadata;
}
@Override
public void setBeanExpressionResolver(@Nullable BeanExpressionResolver resolver) {
this.beanExpressionResolver = resolver;
}
@Override
@Nullable
public BeanExpressionResolver getBeanExpressionResolver() {
return this.beanExpressionResolver;
}
@Override
public void setConversionService(@Nullable ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
@Nullable
public ConversionService getConversionService() {
return this.conversionService;
}
@Override
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
this.propertyEditorRegistrars.add(registrar);
}
/**
* Return the set of PropertyEditorRegistrars.
*/
public Set getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void registerCustomEditor(Class> requiredType, Class extends PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.notNull(propertyEditorClass, "PropertyEditor class must not be null");
this.customEditors.put(requiredType, propertyEditorClass);
}
@Override
public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
registerCustomEditors(registry);
}
/**
* Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
*/
public Map, Class extends PropertyEditor>> getCustomEditors() {
return this.customEditors;
}
@Override
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
}
/**
* Return the custom TypeConverter to use, if any.
* @return the custom TypeConverter, or {@code null} if none specified
*/
@Nullable
protected TypeConverter getCustomTypeConverter() {
return this.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;
}
}
@Override
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
Assert.notNull(valueResolver, "StringValueResolver must not be null");
this.embeddedValueResolvers.add(valueResolver);
}
@Override
public boolean hasEmbeddedValueResolver() {
return !this.embeddedValueResolvers.isEmpty();
}
@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;
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
// Remove from old position, if any
this.beanPostProcessors.remove(beanPostProcessor);
// Add to end of list
this.beanPostProcessors.add(beanPostProcessor);
}
/**
* 添加将应用于由该工厂创建的bean的新的BeanPostProcessors。
* 在工厂配置期间调用。
* @since 5.3
* @see #addBeanPostProcessor
*/
public void addBeanPostProcessors(Collection extends BeanPostProcessor> beanPostProcessors) {
this.beanPostProcessors.removeAll(beanPostProcessors);
this.beanPostProcessors.addAll(beanPostProcessors);
}
@Override
public int getBeanPostProcessorCount() {
return this.beanPostProcessors.size();
}
/**
* 返回将应用于此工厂创建的bean的BeanPostProcessors列表。
*/
public List getBeanPostProcessors() {
return this.beanPostProcessors;
}
/**
* 如果需要,返回预过滤后处理器的内部缓存,如果没有则构建一个新的。
* @since 5.3
*/
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;
}
/**
* 返回该工厂是否持有一个AwareBeanPostProcessor的实例 ,
* 该实例化将在创建时应用于单例bean。
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
*/
protected boolean hasInstantiationAwareBeanPostProcessors() {
return !getBeanPostProcessorCache().instantiationAware.isEmpty();
}
/**
* 返回该工厂是否持有一个DestructionAwareBeanPostProcessor ,
* 该DestructionAwareBeanPostProcessor 将在关闭时应用于单例bean。.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean hasDestructionAwareBeanPostProcessors() {
return !getBeanPostProcessorCache().destructionAware.isEmpty();
}
@Override
public void registerScope(String scopeName, Scope scope) {
Assert.notNull(scopeName, "Scope identifier must not be null");
Assert.notNull(scope, "Scope must not be null");
if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
}
Scope previous = this.scopes.put(scopeName, scope);
if (previous != null && previous != scope) {
if (logger.isDebugEnabled()) {
logger.debug("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
}
}
}
@Override
public String[] getRegisteredScopeNames() {
return StringUtils.toStringArray(this.scopes.keySet());
}
@Override
@Nullable
public Scope getRegisteredScope(String scopeName) {
Assert.notNull(scopeName, "Scope identifier must not be null");
return this.scopes.get(scopeName);
}
/**
* 为这个bean工厂设置安全上下文提供程序。如果设置了安全管理器,
* 则使用提供的安全上下文的特权执行与用户代码的交互。
*/
public void setSecurityContextProvider(SecurityContextProvider securityProvider) {
this.securityContextProvider = securityProvider;
}
/**
* 将访问控制上下文的创建委托给
* {@link #setSecurityContextProvider SecurityContextProvider}.
*/
@Override
public AccessControlContext getAccessControlContext() {
return (this.securityContextProvider != null ?
this.securityContextProvider.getAccessControlContext() :
AccessController.getContext());
}
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
Assert.notNull(otherFactory, "BeanFactory must not be null");
setBeanClassLoader(otherFactory.getBeanClassLoader());
setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
setConversionService(otherFactory.getConversionService());
if (otherFactory instanceof AbstractBeanFactory) {
AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
this.customEditors.putAll(otherAbstractFactory.customEditors);
this.typeConverter = otherAbstractFactory.typeConverter;
this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
this.scopes.putAll(otherAbstractFactory.scopes);
this.securityContextProvider = otherAbstractFactory.securityContextProvider;
}
else {
setTypeConverter(otherFactory.getTypeConverter());
String[] otherScopeNames = otherFactory.getRegisteredScopeNames();
for (String scopeName : otherScopeNames) {
this.scopes.put(scopeName, otherFactory.getRegisteredScope(scopeName));
}
}
}
/**
* 返回给定bean名称的“合并的” BeanDefinition,
* 如有必要,将子bean定义与其父级合并。
* 此{@code getMergedBeanDefinition}也考虑祖先的bean定义
* @param name 用于检索的合并定义的bean的名称(可能是别名)
* @return 返回给定bean的(可能合并的)RootBeanDefinition
* @throws NoSuchBeanDefinitionException 如果没有给定名称的bean
* @throws BeanDefinitionStoreException 在无效的bean定义的情况下
*/
@Override
public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
String beanName = transformedBeanName(name);
// Efficiently check whether bean definition exists in this factory.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
}
// Resolve merged bean definition locally.
return getMergedLocalBeanDefinition(beanName);
}
@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));
}
@Override
public boolean isActuallyInCreation(String beanName) {
return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
}
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set>) curVal).contains(beanName))));
}
/**
* 原型Bean创建前的回调。默认实现将原型注册为当前创建中。
* @param beanName 将要创建的原型Bean的名称
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void beforePrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal == null) {
this.prototypesCurrentlyInCreation.set(beanName);
}
else if (curVal instanceof String) {
Set beanNameSet = new HashSet<>(2);
beanNameSet.add((String) curVal);
beanNameSet.add(beanName);
this.prototypesCurrentlyInCreation.set(beanNameSet);
}
else {
Set beanNameSet = (Set) curVal;
beanNameSet.add(beanName);
}
}
/**
* 原型创建后的回调。默认实现将原型标记为不再创建。
* @param beanName 已创建的原型的名称
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void afterPrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal instanceof String) {
this.prototypesCurrentlyInCreation.remove();
}
else if (curVal instanceof Set) {
Set beanNameSet = (Set) curVal;
beanNameSet.remove(beanName);
if (beanNameSet.isEmpty()) {
this.prototypesCurrentlyInCreation.remove();
}
}
}
@Override
public void destroyBean(String beanName, Object beanInstance) {
destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
}
/**
* 根据给定bean定义销毁给定bean实例(通常是从该工厂获得的原型实例)。
* @param beanName bean定义的名称
* @param bean 要销毁的bean实例
* @param mbd 合并的bean定义
*/
protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, getAccessControlContext()).destroy();
}
@Override
public void destroyScopedBean(String beanName) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isSingleton() || mbd.isPrototype()) {
throw new IllegalArgumentException(
"Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
}
String scopeName = mbd.getScope();
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'");
}
Object bean = scope.remove(beanName);
if (bean != null) {
destroyBean(beanName, bean, mbd);
}
}
//---------------------------------------------------------------------
// Implementation methods
//---------------------------------------------------------------------
/**
* 返回bean名称,必要时去掉工厂解引用前缀,并将别名解析为规范名称。
* @param name 命名用户指定的名称
* @return 返回转换后的bean名称
*/
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
/**
* 确定初始bean名称,将本地定义的别名解析为规范名称。
* @param name 指定的名称
* @return 返回原始bean名称
*/
protected String originalBeanName(String name) {
String beanName = transformedBeanName(name);
if (name.startsWith(FACTORY_BEAN_PREFIX)) {
beanName = FACTORY_BEAN_PREFIX + beanName;
}
return beanName;
}
/**
* 使用在该工厂注册的自定义编辑器初始化给定的BeanWrapper。
* 被BeanWrappers调用,它将创建并填充bean实例。
* 默认实现委托给{@link #registerCustomEditors}。
* 可以在子类中覆盖。
* @param bw 要初始化的BeanWrapper
*/
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(getConversionService());
registerCustomEditors(bw);
}
/**
* 使用已在此BeanFactory中注册的自定义编辑器
* 初始化给定的PropertyEditorRegistry。
* 将为将创建并填充bean实例的BeanWrappers,
* 以及用于构造函数参数和工厂方法类型转换的SimpleTypeConverter调用。
* @param registry 注册PropertyEditorRegistry来初始化
*/
protected void registerCustomEditors(PropertyEditorRegistry registry) {
PropertyEditorRegistrySupport registrySupport =
(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
if (registrySupport != null) {
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
String bceBeanName = bce.getBeanName();
if (bceBeanName != null && isCurrentlyInCreation(bceBeanName)) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
if (!this.customEditors.isEmpty()) {
this.customEditors.forEach((requiredType, editorClass) ->
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass)));
}
}
/**
* 返回合并的RootBeanDefinition,遍历父beanDefinition
* 如果指定的bean对应于子beanDefinition。
* @param beanName 要检索给定bean的合并定义的bean的名称
* @return 返回给定bean的(可能合并的)RootBeanDefinition
* @throws NoSuchBeanDefinitionException 如果没有给定名字的bean
* @throws BeanDefinitionStoreException 在无效bean定义的情况下
*/
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null && !mbd.stale) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
/**
* 如果给定的顶级bean是子bean定义,则通过与父项合并返回RootBeanDefinition。
* @param beanName bean定义的名称
* @param bd 原始bean定义(Root / ChildBeanDefinition)
* @return 返回给定bean的(可能合并的)RootBeanDefinition
* @throws BeanDefinitionStoreException 在无效的bean定义的情况下
*/
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
/**
* 如果给定bean的定义是子beanDefinition,则通过与父beanDefinition合并,
* 返回给定bean的RootBeanDefinition。
* @param beanName Bean定义的名称
* @param bd 原始bean定义(Root / ChildBeanDefinition)
* @param containingBd 如果是内部bean,则为包含bean的定义;
* 如果是top-,则为{@code null}级别bean
* @return 返回给定bean的RootBeanDefinition(可能合并)RootBeanDefinition
* @throws BeanDefinitionStoreException 如果bean定义无效
*/
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
RootBeanDefinition previous = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null || mbd.stale) {
previous = mbd;
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without a ConfigurableBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Cache the merged bean definition for the time being
// (it might still get re-merged later on in order to pick up metadata changes)
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
if (previous != null) {
copyRelevantMergedBeanDefinitionCaches(previous, mbd);
}
return mbd;
}
}
private void copyRelevantMergedBeanDefinitionCaches(RootBeanDefinition previous, RootBeanDefinition mbd) {
if (ObjectUtils.nullSafeEquals(mbd.getBeanClassName(), previous.getBeanClassName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryBeanName(), previous.getFactoryBeanName()) &&
ObjectUtils.nullSafeEquals(mbd.getFactoryMethodName(), previous.getFactoryMethodName())) {
ResolvableType targetType = mbd.targetType;
ResolvableType previousTargetType = previous.targetType;
if (targetType == null || targetType.equals(previousTargetType)) {
mbd.targetType = previousTargetType;
mbd.isFactoryBean = previous.isFactoryBean;
mbd.resolvedTargetType = previous.resolvedTargetType;
mbd.factoryMethodReturnType = previous.factoryMethodReturnType;
mbd.factoryMethodToIntrospect = previous.factoryMethodToIntrospect;
}
}
}
/**
* 检查给定的合并beanDefinition,可能抛出验证异常。
* @param mbd 检查合并的bean定义
* @param beanName bean的名称
* @param args 创建bean的参数(如果有的话)
* @throws BeanDefinitionStoreException 在验证失败的情况下
*/
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, @Nullable Object[] args)
throws BeanDefinitionStoreException {
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
}
/**
* 删除指定bean的合并bean定义,在下次访问时重新创建。
* @param beanName 要清除的MergedBeanDefinition
*/
protected void clearMergedBeanDefinition(String beanName) {
RootBeanDefinition bd = this.mergedBeanDefinitions.get(beanName);
if (bd != null) {
bd.stale = true;
}
}
/**
* 清除合并的beanDefinition缓存,删除bean的条目
* 尚不适合完全元数据缓存的bean。
* 通常在更改原始bean定义后触发,例如应用{@code BeanFactoryPostProcessor}
* 之后。请注意,此时将保留已创建的bean的元数据
* @since 4.2
*/
public void clearMetadataCache() {
this.mergedBeanDefinitions.forEach((beanName, bd) -> {
if (!isBeanEligibleForMetadataCaching(beanName)) {
bd.stale = true;
}
});
}
/**
* 为指定的beanDefinition解析为bean Class,
* 将bean类名称解析为Class引用(如果需要)
* 并将解析后的Class存储在beanDefinition中以供进一步使用。
* @param mbd 合并的beanDefinition,以确定类
* @param beanName bean的名称(出于错误处理目的)
* @param typesToMatch 类型以在内部类型匹配的情况下进行匹配
* (还表示返回{@code Class}永远不会暴露给应用程序代码)
* @return 返回已解析的bean类(如果没有则返回{@code null})
* @throws CannotLoadBeanClassException 如果我们无法加载该类
*/
@Nullable
protected Class> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class>... typesToMatch)
throws CannotLoadBeanClassException {
try {
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedExceptionAction>) () ->
doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}
@Nullable
private Class> doResolveBeanClass(RootBeanDefinition mbd, Class>... typesToMatch)
throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader dynamicLoader = beanClassLoader;
boolean freshResolve = false;
if (!ObjectUtils.isEmpty(typesToMatch)) {
// When just doing type checks (i.e. not creating an actual instance yet),
// use the specified temporary class loader (e.g. in a weaving scenario).
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
dynamicLoader = tempClassLoader;
freshResolve = true;
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (Class> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
}
}
String className = mbd.getBeanClassName();
if (className != null) {
Object evaluated = evaluateBeanDefinitionString(className, mbd);
if (!className.equals(evaluated)) {
// A dynamically resolved expression, supported as of 4.2...
if (evaluated instanceof Class) {
return (Class>) evaluated;
}
else if (evaluated instanceof String) {
className = (String) evaluated;
freshResolve = true;
}
else {
throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
}
if (freshResolve) {
// When resolving against a temporary class loader, exit early in order
// to avoid storing the resolved Class in the bean definition.
if (dynamicLoader != null) {
try {
return dynamicLoader.loadClass(className);
}
catch (ClassNotFoundException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Could not load class [" + className + "] from " + dynamicLoader + ": " + ex);
}
}
}
return ClassUtils.forName(className, dynamicLoader);
}
}
// Resolve regularly, caching the result in the BeanDefinition...
return mbd.resolveBeanClass(beanClassLoader);
}
/**
* 计算beanDefinition中包含的给定String,
* 可能将其解析为表达式。
* @param value 要检查的值
* @param beanDefinition 该值来自的beanDefinition
* @return 返回解析后的值
* @see #setBeanExpressionResolver
*/
@Nullable
protected Object evaluateBeanDefinitionString(@Nullable String value, @Nullable BeanDefinition beanDefinition) {
if (this.beanExpressionResolver == null) {
return value;
}
Scope scope = null;
if (beanDefinition != null) {
String scopeName = beanDefinition.getScope();
if (scopeName != null) {
scope = getRegisteredScope(scopeName);
}
}
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
/**
* 预测指定bean的最终bean类型(已处理bean实例的类型)。
* 由{@link #getType}和{@link #isTypeMatch}调用。
* 不需要专门处理FactoryBeans,因为应该仅对原始bean类型进行操作。
* 此实现非常简单,因为它无法处理工厂方法和
* InstantiationAwareBeanPostProcessors。 它只能正确预测标准bean的bean类型。
* 在子类中被覆盖,应用更复杂的类型检测。
* @param beanName bean的名称
* @param mbd 合并的bean定义来确定类型
* @param typesToMatch 匹配类型以在内部类型匹配的情况下匹配
* (还表示返回的{@code Class}将永远不会暴露给应用程序代码)
* @return 返回bean的类型,如果不可预测,则返回{@code null}
*/
@Nullable
protected Class> predictBeanType(String beanName, RootBeanDefinition mbd, Class>... typesToMatch) {
Class> targetType = mbd.getTargetType();
if (targetType != null) {
return targetType;
}
if (mbd.getFactoryMethodName() != null) {
return null;
}
return resolveBeanClass(mbd, beanName, typesToMatch);
}
/**
* 检查给定的bean是否已定义为{@link FactoryBean}。
* @param beanName bean的名称
* @param mbd 对应的bean定义
*/
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
Boolean result = mbd.isFactoryBean;
if (result == null) {
Class> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
result = (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
mbd.isFactoryBean = result;
}
return result;
}
/**
* 尽可能确定给定FactoryBean定义的bean类型。
* 仅在尚未为目标bean注册单例实例时调用。只有在{@code allowInit}为{@code true}
* 的情况下,实现才可以实例化工厂bean,否则实现应尝试通过其他方式确定结果。
* 如果未在BeanDefinition上设置
* {@link FactoryBean#OBJECT_TYPE_ATTRIBUTE},并且{@code allowInit}为
* {@code true},则默认实现将通过{@code getBean}创建FactoryBean来调用它
* {@code getObjectType}方法。鼓励子类优化此操作,通常通过检查工厂bean类的
* 通用签名或创建它的工厂方法来进行优化。如果子类确实实例化了FactoryBean,
* 则应考虑在未完全填充Bean的情况下尝试{@code getObjectType}方法。
* 如果失败,则应将此实现执行的完全FactoryBean创建用作回退。
* @param beanName tbean的名称
* @param mbd bean的合并后的beanDefinition
* @param allowInit (如果允许初始化FactoryBean)
* @return 返回可确定的bean类型,否则返回{@code ResolvableType.NONE}
* @since 5.2
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
*/
protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
if (result != ResolvableType.NONE) {
return result;
}
if (allowInit && mbd.isSingleton()) {
try {
FactoryBean> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
Class> objectType = getTypeForFactoryBean(factoryBean);
return (objectType != null) ? ResolvableType.forClass(objectType) : ResolvableType.NONE;
}
catch (BeanCreationException ex) {
if (ex.contains(BeanCurrentlyInCreationException.class)) {
logger.trace(LogMessage.format("Bean currently in creation on FactoryBean type check: %s", ex));
}
else if (mbd.isLazyInit()) {
logger.trace(LogMessage.format("Bean creation exception on lazy FactoryBean type check: %s", ex));
}
else {
logger.debug(LogMessage.format("Bean creation exception on non-lazy FactoryBean type check: %s", ex));
}
onSuppressedException(ex);
}
}
return ResolvableType.NONE;
}
/**
* 通过检查{@ link FactoryBean#OBJECT_TYPE_ATTRIBUTE}值的属性来
* 确定FactoryBean的bean类型。
* @param attributes 为要检查的属性赋予属性
* @return 返回从属性中提取的{@link ResolvableType}或
* {@code ResolvableType.NONE}
* @since 5.2
*/
ResolvableType getTypeForFactoryBeanFromAttributes(AttributeAccessor attributes) {
Object attribute = attributes.getAttribute(FactoryBean.OBJECT_TYPE_ATTRIBUTE);
if (attribute instanceof ResolvableType) {
return (ResolvableType) attribute;
}
if (attribute instanceof Class) {
return ResolvableType.forClass((Class>) attribute);
}
return ResolvableType.NONE;
}
/**
* 尽可能确定给定FactoryBean定义的bean类型。
* 仅在尚未为目标bean注册单例实例时调用。
* 默认实现通过{@code getBean}创建FactoryBean来调用其{@code getObjectType}
* 方法。鼓励子类优化此操作,通常只实例化FactoryBean而不填充它,然后尝试其
* {@code getObjectType}方法是否已经返回类型。 如果未找到类型,则应使用此实
* 现执行的完整FactoryBean创建作为后备。
* @param beanName bean的名称
* @param mbd 合并后的beanDefinition
* @return 返回bean的类型(如果可以确定的话),否则返回{@code null}
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
* @deprecated since 5.2 in favor of {@link #getTypeForFactoryBean(String, RootBeanDefinition, boolean)}
*/
@Nullable
@Deprecated
protected Class> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
return getTypeForFactoryBean(beanName, mbd, true).resolve();
}
/**
* 将指定的bean标记为已创建(或将要创建)。
* 这允许bean工厂优化其缓存以重复创建指定的bean。
* @param beanName bean的名称
*/
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
/**
* 在bean创建失败后,对缓存的元数据执行适当的清理。
* @param beanName bean的名称
*/
protected void cleanupAfterBeanCreationFailure(String beanName) {
synchronized (this.mergedBeanDefinitions) {
this.alreadyCreated.remove(beanName);
}
}
/**
* 确定指定的bean是否有资格缓存它的bean定义元数据。
* @param beanName bean的名称
* @return 返回{@code true},如果此时可能已经缓存了bean的元数据
* at this point already
*/
protected boolean isBeanEligibleForMetadataCaching(String beanName) {
return this.alreadyCreated.contains(beanName);
}
/**
* 删除给定bean名称的单例实例(如果有的话),但仅当它没有用于类型检查之外
* 的其他目的时才删除。
* @param beanName bean的名称
* @return 如果实际删除,返回{@code true},否则返回{@code false}
*/
protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
removeSingleton(beanName);
return true;
}
else {
return false;
}
}
/**
* 检查该工厂的bean创建阶段是否已经开始,也就是说,在此期间是否有任何bean
* 被标记为已创建。
* @since 4.2.2
* @see #markBeanAsCreated
*/
protected boolean hasBeanCreationStarted() {
return !this.alreadyCreated.isEmpty();
}
/**
* 获取给定bean实例的对象,对于FactoryBean,可以是bean 实例本身,
* 也可以是它创建的对象。
* @param beanInstance 共享bean实例
* @param name 可能包含工厂解除引用前缀的名称
* @param beanName 规范bean名
* @param mbd t合并的beanDefinition
* @return 返回要为bean公开的对象
*/
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.
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.
if (!(beanInstance instanceof FactoryBean)) {
return beanInstance;
}
Object object = null;
if (mbd != null) {
mbd.isFactoryBean = true;
}
else {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
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());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
/**
* 确定给定的bean名称是否已经在这个工厂中使用,即是否有一个本地bean或别名
* 在这个名称下注册,或者一个用这个名称创建的内部bean。
* @param beanName 要检查的名称
*/
public boolean isBeanNameInUse(String beanName) {
return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
}
/**
* 确定给定bean在关闭时是否需要销毁。默认实现检查一次性bean接口以及指定的
* 销毁方法和注册的
* @param bean 要检查的bean实例
* @param mbd 对应的bean定义
* @see org.springframework.beans.factory.DisposableBean
* @see AbstractBeanDefinition#getDestroyMethodName()
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
return (bean.getClass() != NullBean.class && (DisposableBeanAdapter.hasDestroyMethod(bean, mbd) ||
(hasDestructionAwareBeanPostProcessors() && DisposableBeanAdapter.hasApplicableProcessors(
bean, getBeanPostProcessorCache().destructionAware))));
}
/**
* 将给定的bean添加到这个工厂的一次性bean列表中,注册其DisposableBean接口
* 和给定的销毁方法。在工厂关闭时调用(如适用)。只适用于单例。
* @param beanName bean的名称
* @param bean bean实例
* @param mbd bean的beanDefinition
* @see RootBeanDefinition#isSingleton
* @see RootBeanDefinition#getDependsOn
* @see #registerDisposableBean
* @see #registerDependentBean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName, new DisposableBeanAdapter(
bean, beanName, mbd, getBeanPostProcessorCache().destructionAware, acc));
}
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, getBeanPostProcessorCache().destructionAware, acc));
}
}
}
//---------------------------------------------------------------------
// Abstract methods to be implemented by subclasses
//---------------------------------------------------------------------
/**
* 检查此bean工厂是否包含具有给定名称的beanDefinition。
* 不考虑该工厂可能参与的任何层次结构。
* 当未找到缓存的单例实例时,由{@code containsBean}调用。
* 根据具体bean工厂实现的性质,此操作可能很昂贵(例如,由于外部注册表中的
* 目录查找)。但是,对于可列出的bean工厂,这通常只相当于本地哈希查找:因
* 此,该操作是该地方的public接口的一部分。在这种情况下,此模板方法和公共接
* 口方法都可以使用相同的实现。
* @param beanName 要查找的bean的名称
* @return 返回此bean工厂是否包含具有给定名称的beanDefinition
* @see #containsBean
* @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition
*/
protected abstract boolean containsBeanDefinition(String beanName);
/**
* 返回给定bean名称的beanDefinition。子类通常应该实现缓存,因为每次需要
* beanDefinition元数据时,此类都会调用该方法。
* 根据具体bean工厂实现的性质,此操作可能很昂贵(例如,由于外部注册表中的
* 目录查找)。但是,对于可列出的bean工厂,这通常只相当于本地哈希查找:因
* 此,该操作是该地方的public接口的一部分。在这种情况下,此模板方法和公共接
* 口方法都可以使用相同的实现。
* @param beanName 要为其查找BeanDefinition的bean的名称
* @return 返回原型名称的BeanDefinition (never {@code null})
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* 如果无法解析bean定义
* @throws BeansException in case of errors
* @see RootBeanDefinition
* @see ChildBeanDefinition
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition
*/
protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
/**
* 为给定的合并beanDefinition(和参数)创建一个bean实例。
* 如果是子的BeanDefinition,则beanDefinition将已经与父的BeanDefinition合并。
* 所有bean检索方法都委托该方法进行实际的bean创建。
* @param beanName bean的名称
* @param mbd bean合并的beanDefinition
* @param args 用于构造函数或工厂方法调用的显式参数
* @return 返回bean的一个新实例
* @throws BeanCreationException 如果bean不能被创建
*/
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
/**
* CopyOnWriteArrayList which resets the beanPostProcessorCache field on modification.
*
* @since 5.3
*/
private class BeanPostProcessorCacheAwareList extends CopyOnWriteArrayList {
@Override
public BeanPostProcessor set(int index, BeanPostProcessor element) {
BeanPostProcessor result = super.set(index, element);
beanPostProcessorCache = null;
return result;
}
@Override
public boolean add(BeanPostProcessor o) {
boolean success = super.add(o);
beanPostProcessorCache = null;
return success;
}
@Override
public void add(int index, BeanPostProcessor element) {
super.add(index, element);
beanPostProcessorCache = null;
}
@Override
public BeanPostProcessor remove(int index) {
BeanPostProcessor result = super.remove(index);
beanPostProcessorCache = null;
return result;
}
@Override
public boolean remove(Object o) {
boolean success = super.remove(o);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public boolean removeAll(Collection> c) {
boolean success = super.removeAll(c);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public boolean retainAll(Collection> c) {
boolean success = super.retainAll(c);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public boolean addAll(Collection extends BeanPostProcessor> c) {
boolean success = super.addAll(c);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public boolean addAll(int index, Collection extends BeanPostProcessor> c) {
boolean success = super.addAll(index, c);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public boolean removeIf(Predicate super BeanPostProcessor> filter) {
boolean success = super.removeIf(filter);
if (success) {
beanPostProcessorCache = null;
}
return success;
}
@Override
public void replaceAll(UnaryOperator operator) {
super.replaceAll(operator);
beanPostProcessorCache = null;
}
};
/**
* Internal cache of pre-filtered post-processors.
*
* @since 5.3
*/
static class BeanPostProcessorCache {
final List instantiationAware = new ArrayList<>();
final List smartInstantiationAware = new ArrayList<>();
final List destructionAware = new ArrayList<>();
final List mergedDefinition = new ArrayList<>();
}
}