本文尝试分析一下Spring 的BeanFactory 体系的 接口设计,尝试理解为什么这么做,为什么接口这么设计、为什么这么去实现,为什么需要有这个方法,为什么 这样命名?接口、类、方法的 大致用途是什么? 是否是最合理的?是否有完善的空间? 是否 让一个 同样顶级人才来设计,是否会得到一样的 设计和实现?
简称:
BeanFactory 简称bf
ApplicationContext 简称ac
ServletContext 简称sc
BeanDefinition 简称bd
接口/类图
bf的 uml 接口/类图 如下:
接口说明
================================================================== BeanFactory ====================================================================================================
BeanFactory(简称bf,下同) 无疑是Spring最最最基础的bean工厂,所以呢,它提供了最最最基础、最最最常用(也是必须的)的接口:
通过名字获取bean,通过类型获取bean,通过名字、参数获取bean, 通过类型、参数获取bean,
是否包含给定名字的bean,通过bean名字判断其是否 单例,通过bean名字获取类型
判断给定名字的bean是否具有对应类型(ResolvableType、Class),通过名字获取别名
———— 注意到bf 的get接口返回的都是 单个bean ,而且 返回的是实例!
———— 注意到bf 几乎全是get接口,没有set,why? 让bf简单化,纯粹化。只管获取,具体的创建 等工作 交由了子接口、具体类去实现。。
ps: 个人认为这个接口设计得非常好! 方法不多不少,毫无多余,毫无遗漏!参数、返回值,不多不少,命名极为工整、规范!
public interface BeanFactory {
String FACTORY_BEAN_PREFIX = "&";
Object getBean(String var1) throws BeansException;
<T> T getBean(String var1, @Nullable Class<T> var2) throws BeansException;
Object getBean(String var1, Object... var2) throws BeansException;
<T> T getBean(Class<T> var1) throws BeansException;
<T> T getBean(Class<T> var1, Object... var2) throws BeansException;
boolean containsBean(String var1);
boolean isSingleton(String var1) throws NoSuchBeanDefinitionException;
boolean isPrototype(String var1) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String var1, ResolvableType var2) throws NoSuchBeanDefinitionException;
boolean isTypeMatch(String var1, @Nullable Class<?> var2) throws NoSuchBeanDefinitionException;
@Nullable
Class<?> getType(String var1) throws NoSuchBeanDefinitionException;
String[] getAliases(String var1);
}
================================================================== ListableBeanFactory ============================================================================================
ListableBeanFactory 有2个属性:
Listable?可list?可列举的;可列表的。什么可列举? 可以认为BeanName 可列举,还有就是: 它有哪些bean,什么名字,个数多少,哪些bean definition,各个类型bean ,有什么样的注解..
ListableBeanFactory 涉及到BeanDefinition,(简称bd,下同)为什么。这个Listable 应该同 DefaultListableBeanFactory, 主要针对 bean definition
具体来说:
是否包含给定名字的bd,获取bd个数,获取bd names数组集合,
通过类型获取 名字集合,通过类型获取 名字&实例集合,存在多个重载的方法,后面两个boolean 参数分别是表示?
通过注解获取 名字集合,通过注解获取 名字&实例集合,
通过类型、参数获取bean上的注解
allowEagerInit 有些不好解释,留到后面再说
// public String[] getBeanNamesForType(@Nullable Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
———— 为什么 没有获取bd 的方法,而是仅仅 获取bd names数组集合? 由 其他的bf 提供
———— 为什么这些接口, 不移动部分到bf中去? 个人感觉可能 没必要,让接口的方法精简 会更好! 分工要明确, 这样,接口的实现 才会 更加方便!
??ResolvableType 和 Class 什么区别,为什么会 ResolvableType?
public interface ListableBeanFactory extends BeanFactory {
boolean containsBeanDefinition(String var1);
int getBeanDefinitionCount();
String[] getBeanDefinitionNames();
String[] getBeanNamesForType(ResolvableType var1);
String[] getBeanNamesForType(@Nullable Class<?> var1);
String[] getBeanNamesForType(@Nullable Class<?> var1, boolean includeNonSingletons, boolean allowEagerInit);
<T> Map<String, T> getBeansOfType(@Nullable Class<T> var1) throws BeansException;
<T> Map<String, T> getBeansOfType(@Nullable Class<T> var1, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException;
String[] getBeanNamesForAnnotation(Class<? extends Annotation> var1);
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> var1) throws BeansException;
@Nullable
<A extends Annotation> A findAnnotationOnBean(String var1, Class<A> var2) throws NoSuchBeanDefinitionException;
================================================================== ConfigurableBeanFactory ============================================================================================
ConfigurableBeanFactory 继承了 HierarchicalBeanFactory, SingletonBeanRegistry。 另外 ClassLoader ,为什么要有ClassLoader 而且TempClassLoader ?
这个Configurable bf呢,什么东西 Configurable呢? 如下。另外需要注意的是 他默认提供了 2个 scope 的支持。分别是 单例、原型。 而且还可以注册 scope,这个在 web ac中有用到。
简单属性有:
parentBeanFactory: BeanFactory
beanClassLoader: ClassLoader
tempClassLoader: ClassLoader
cacheBeanMetadata: boolean
beanExpressionResolver: BeanExpressionResolver
conversionService: ConversionService
typeConverter: TypeConverter
beanPostProcessorCount: int // getter
registeredScopeNames: String[]
accessControlContext: AccessControlContext // getter
简单方法有:增加PropertyEditorRegistrar、CustomEditor、EmbeddedValueResolver、BeanPostProcessor、scope、Alias
addPropertyEditorRegistrar
registerCustomEditor
copyRegisteredEditorsTo
addEmbeddedValueResolver
hasEmbeddedValueResolver
resolveEmbeddedValue //
addBeanPostProcessor
registerScope //
getRegisteredScope
copyConfigurationFrom
registerAlias //
resolveAliases //
getMergedBeanDefinition //
isFactoryBean // 工厂bean
setCurrentlyInCreation //
isCurrentlyInCreation
registerDependentBean //
getDependentBeans //
getDependenciesForBean //
destroyBean // 此方法有两个参数
destroyScopedBean
destroySingletons
public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
String SCOPE_SINGLETON = "singleton";
String SCOPE_PROTOTYPE = "prototype";
void setParentBeanFactory(BeanFactory var1) throws IllegalStateException;
void setBeanClassLoader(@Nullable ClassLoader var1);
@Nullable
ClassLoader getBeanClassLoader();
void setTempClassLoader(@Nullable ClassLoader var1);
@Nullable
ClassLoader getTempClassLoader();
void setCacheBeanMetadata(boolean var1);
boolean isCacheBeanMetadata();
void setBeanExpressionResolver(@Nullable BeanExpressionResolver var1);
@Nullable
BeanExpressionResolver getBeanExpressionResolver();
void setConversionService(@Nullable ConversionService var1);
@Nullable
ConversionService getConversionService();
void addPropertyEditorRegistrar(PropertyEditorRegistrar var1);
void registerCustomEditor(Class<?> var1, Class<? extends PropertyEditor> var2);
void copyRegisteredEditorsTo(PropertyEditorRegistry var1);
void setTypeConverter(TypeConverter var1);
TypeConverter getTypeConverter();
void addEmbeddedValueResolver(StringValueResolver var1);
boolean hasEmbeddedValueResolver();
@Nullable
String resolveEmbeddedValue(String var1);
void addBeanPostProcessor(BeanPostProcessor var1);
int getBeanPostProcessorCount();
void registerScope(String var1, Scope var2);
String[] getRegisteredScopeNames();
@Nullable
Scope getRegisteredScope(String var1);
AccessControlContext getAccessControlContext();
void copyConfigurationFrom(ConfigurableBeanFactory var1);
void registerAlias(String var1, String var2) throws BeanDefinitionStoreException;
void resolveAliases(StringValueResolver var1);
BeanDefinition getMergedBeanDefinition(String var1) throws NoSuchBeanDefinitionException;
boolean isFactoryBean(String var1) throws NoSuchBeanDefinitionException;
void setCurrentlyInCreation(String var1, boolean var2);
boolean isCurrentlyInCreation(String var1);
void registerDependentBean(String var1, String var2);
String[] getDependentBeans(String var1);
String[] getDependenciesForBean(String var1);
void destroyBean(String var1, Object var2);
void destroyScopedBean(String var1);
void destroySingletons();
}
================================================================== HierarchicalBeanFactory ============================================================================================
HierarchicalBeanFactory 很简单,它相当于 仅仅一个 parentBeanFactory 属性, 以及检查是否本地(就是 自己!)就包含了某个name的bean
public interface HierarchicalBeanFactory extends BeanFactory {
@Nullable
BeanFactory getParentBeanFactory();
boolean containsLocalBean(String var1);
}
================================================================== AutowireCapableBeanFactory ============================================================================================
AutowireCapable ,支持 Autowire 特性,主要是 3种的Autowire 方式(非注解)。。
是不是只要 autowire 相关的方法就足够了呢? 其他的方法, 有何必要?
createBean 的首次定义,正是此接口。为什么 定义此处?
另外还有方法configureBean?
autowire 无疑是非常关键的方法,
autowireBeanProperties 表示自动的 注入bean属性
applyBeanPropertyValues 两者的名字,作用 看起来这么的接近。。我估计autowireBeanProperties 应该是调用了本方法。
initializeBean applyBeanPostProcessorsBeforeInitialization applyBeanPostProcessorsAfterInitialization 几个方法定义了 bean 初始化前、中、后的 基本行为模式,
destroyBean bean使用完后销毁
resolveDependency 通过 DependencyDescriptor requestingBeanName,
为什么要定义 两个resolveDependency方法?因为 ... autowire 的时候,可能很复杂,需要计算 依赖关系吧。
resolveNamedBean 是通过一个Class返回
为什么createBean、initializeBean、applyBeanPostProcessorsBeforeInitialization、applyBeanPostProcessorsAfterInitialization、destroyBean 等方法定义于此? 因为 定义在其他接口也不太方便吧。。而且它有autowireBean,自然能够createBean,从而也可以destroy..
public interface AutowireCapableBeanFactory extends BeanFactory {
int AUTOWIRE_NO = 0;
int AUTOWIRE_BY_NAME = 1;
int AUTOWIRE_BY_TYPE = 2;
int AUTOWIRE_CONSTRUCTOR = 3;
/** @deprecated */
@Deprecated
int AUTOWIRE_AUTODETECT = 4;
<T> T createBean(Class<T> beanClass) throws BeansException;
void autowireBean(Object existingBean) throws BeansException;
Object configureBean(Object existingBean, String beanName) throws BeansException;
Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException;
void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck) throws BeansException;
void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException;
Object initializeBean(Object existingBean, String beanName) throws BeansException;
Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException;
Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException;
void destroyBean(Object existingBean);
<T> NamedBeanHolder<T> resolveNamedBean(Class<T> requiredType) throws BeansException;
@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException;
@Nullable
Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName, @Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException;
}
================================================================== ConfigurableListableBeanFactory ============================================================================================
ConfigurableListableBeanFactory 又是Configurable 又是Listable。其实我们发现Configurable bf、Listable bf 都是存在的,为什么不直接继承 这两个bf,而是要另外创建一个ConfigurableListable bf呢? 它确实继承了直接继承 这两个bf,而且继承了 AutowireCapable bf。 看看他有什么新方法:
有2个ignore方法,
我的理解是 继承Configurable bf、Listable bf之后,还不算是ConfigurableListable,添加了 更多的方法之后,才是真正的 ConfigurableListable 。。
比如ignoreDependencyXxx 、isAutowireCandidate registerResolvableDependency 方法,是不是放到AutowireCapableBeanFactory 中更好?
getBeanDefinition 的首次定义竟然在这里,隐藏的够深了。。
getBeanNamesIterator 为什么不作为一个私有方法,而是 接口方法?ListableBeanFactory 的get bd names数组集合 不是够了吗?
preInstantiateSingletons 这个方法 无疑是 很重要的, 可以预实例化单例,,为什么出现在这里?
public interface ConfigurableListableBeanFactory extends ListableBeanFactory, AutowireCapableBeanFactory, ConfigurableBeanFactory {
void ignoreDependencyType(Class<?> type);
void ignoreDependencyInterface(Class<?> ifc);
void registerResolvableDependency(Class<?> dependencyType, @Nullable Object autowiredValue);
boolean isAutowireCandidate(String var1, DependencyDescriptor var2) throws NoSuchBeanDefinitionException;
BeanDefinition getBeanDefinition(String beanName) throws NoSuchBeanDefinitionException;
Iterator<String> getBeanNamesIterator();
void clearMetadataCache();
void freezeConfiguration();
boolean isConfigurationFrozen();
void preInstantiateSingletons() throws BeansException;
}
================================================================== SingletonBeanRegistry ============================================================================================
很明显,提供了对Singleton模式即单例bean 的注册,亦即get、contains、register,getXxxCount, 其中getXxMutex 的作用是? 为什么定义在 这个接口里面呢?
public interface SingletonBeanRegistry {
void registerSingleton(String var1, Object var2);
@Nullable
Object getSingleton(String var1);
boolean containsSingleton(String var1);
String[] getSingletonNames();
int getSingletonCount();
Object getSingletonMutex();
}
实现说明
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 接口的实现 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AbstractBeanFactory ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AbstractBeanFactory 实现了 ConfigurableBeanFactory,所以他提供了 基础的各种 可配置化 特性; 外加3个abstract 抽象方法。 其中 getBeanDefinition 、containsBeanDefinition 既在 抽象类中定义, 又在接口里面定义,而且没有直接关系,个人感觉有 设计不良的 倾向。。
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<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet(4);
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap(4);
@Nullable
private TypeConverter typeConverter;
private final List<StringValueResolver> embeddedValueResolvers = new LinkedList();
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList();
private boolean hasInstantiationAwareBeanPostProcessors;
private boolean hasDestructionAwareBeanPostProcessors;
private final Map<String, Scope> scopes = new LinkedHashMap(8);
@Nullable
private SecurityContextProvider securityContextProvider;
private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap(256);
private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap(256));
private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal("Prototype beans currently in creation");
所有的方法如下(有点长,仅供 快速的浏览):
support.AbstractBeanFactory
getBean(java.lang.String)
getBean(java.lang.String, java.lang.Class<T>)
getBean(java.lang.String, java.lang.Object...)
containsBean
isSingleton
isPrototype
isTypeMatch(java.lang.String, org.springframework.core.ResolvableType)
isTypeMatch(java.lang.String, java.lang.Class<?>)
getType
getAliases
containsLocalBean
getParentBeanFactory
addPropertyEditorRegistrar
registerCustomEditor
copyRegisteredEditorsTo
addEmbeddedValueResolver
hasEmbeddedValueResolver
resolveEmbeddedValue
addBeanPostProcessor
registerScope
getRegisteredScope
copyConfigurationFrom
getMergedBeanDefinition(java.lang.String)
isFactoryBean(java.lang.String)
destroyBean(java.lang.String, java.lang.Object)
destroyScopedBean
setParentBeanFactory
setBeanClassLoader
getBeanClassLoader
setTempClassLoader
getTempClassLoader
setCacheBeanMetadata
isCacheBeanMetadata
setBeanExpressionResolver
getBeanExpressionResolver
setConversionService
getConversionService
setTypeConverter
getTypeConverter
getBeanPostProcessorCount
getRegisteredScopeNames
getAccessControlContext
isActuallyInCreation
AbstractBeanFactory()
AbstractBeanFactory(BeanFactory)
getBean(java.lang.String, java.lang.Class<T>, java.lang.Object...)
doGetBean
hasInstantiationAwareBeanPostProcessors
hasDestructionAwareBeanPostProcessors
isPrototypeCurrentlyInCreation
beforePrototypeCreation
afterPrototypeCreation
destroyBean(java.lang.String, java.lang.Object, support.RootBeanDefinition)
transformedBeanName
originalBeanName
initBeanWrapper
registerCustomEditors
getMergedLocalBeanDefinition
getMergedBeanDefinition(java.lang.String, config.BeanDefinition)
getMergedBeanDefinition(java.lang.String, config.BeanDefinition, config.BeanDefinition)
checkMergedBeanDefinition
clearMergedBeanDefinition
clearMetadataCache
resolveBeanClass
doResolveBeanClass
evaluateBeanDefinitionString
predictBeanType
isFactoryBean(java.lang.String, support.RootBeanDefinition)
getTypeForFactoryBean
markBeanAsCreated
cleanupAfterBeanCreationFailure
isBeanEligibleForMetadataCaching
removeSingletonIfCreatedForTypeCheckOnly
hasBeanCreationStarted
getObjectForBeanInstance
isBeanNameInUse
requiresDestruction
registerDisposableBeanIfNecessary
containsBeanDefinition // abstract 抽象方法
getBeanDefinition // 抽象方法
createBean // abstract 抽象方法
//
getPropertyEditorRegistrars
propertyEditorRegistrars
getCustomEditors
customEditors
getBeanPostProcessors
beanPostProcessors
setSecurityContextProvider
securityContextProvider
getCustomTypeConverter
parentBeanFactory
beanClassLoader
tempClassLoader
cacheBeanMetadata
beanExpressionResolver
conversionService
typeConverter
embeddedValueResolvers
hasInstantiationAwareBeanPostProcessors
hasDestructionAwareBeanPostProcessors
scopes
mergedBeanDefinitions
alreadyCreated
prototypesCurrentlyInCreation
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ AbstractAutowireCapableBeanFactory ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
AbstractAutowireCapableBeanFactory 继承abstract bf, 实现了AutowireCapableBeanFactory,可以想象 它主要 提供了 autowire 特性。—— autowire 特性在spring 可以算得上是非常重要的! 一大亮点!
提供了 create 、autowire 、configure apply initialize destroy instantiate populate convert circularReference dependencyCheck 等特性 的基本实现, 是非常 主要的 实现。
它提供了 ignoredDependencyXxx 特性
构造器中添加3个:
this.ignoreDependencyInterface(BeanNameAware.class);
this.ignoreDependencyInterface(BeanFactoryAware.class);
this.ignoreDependencyInterface(BeanClassLoaderAware.class);
为什么它们不需要 检查依赖 dependencyCheck? 因为他们是 框架系统基础、 默认是安全的、、、
—— 但是 它的很多方法没有去实现,比如resolveDependency 重要的方法都没有实现,可以认为它是 非常不完整的。
主要的私有的属性是:
private InstantiationStrategy instantiationStrategy;
@Nullable
private ParameterNameDiscoverer parameterNameDiscoverer;
private boolean allowCircularReferences;
private boolean allowRawInjectionDespiteWrapping;
private final Set<Class<?>> ignoredDependencyTypes;
private final Set<Class<?>> ignoredDependencyInterfaces;
private final NamedThreadLocal<String> currentlyCreatedBean;
private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache;
private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache;
签名是:
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {
}
所有的方法如下:
AbstractAutowireCapableBeanFactory
AutowireByTypeDependencyDescriptor
getDependencyName
AutowireByTypeDependencyDescriptor
copyConfigurationFrom
predictBeanType
getTypeForFactoryBean
getObjectForBeanInstance
createBean
autowireBean
configureBean
resolveDependency
createBean
autowire
autowireBeanProperties
applyBeanPropertyValues
initializeBean
applyBeanPostProcessorsBeforeInitialization
applyBeanPostProcessorsAfterInitialization
destroyBean
createBean
postProcessObjectFromFactoryBean
removeSingleton
clearSingletonCache
AbstractAutowireCapableBeanFactory
AbstractAutowireCapableBeanFactory
ignoreDependencyType
ignoreDependencyInterface
doCreateBean
determineTargetType
getTypeForFactoryMethod
getTypeForFactoryBeanFromMethod
Holder
Holder
value
getEarlyBeanReference
getSingletonFactoryBeanForTypeCheck
getNonSingletonFactoryBeanForTypeCheck
applyMergedBeanDefinitionPostProcessors
resolveBeforeInstantiation
applyBeanPostProcessorsBeforeInstantiation
createBeanInstance
obtainFromSupplier
determineConstructorsFromBeanPostProcessors
instantiateBean
instantiateUsingFactoryMethod
autowireConstructor
populateBean
autowireByName
autowireByType
unsatisfiedNonSimpleProperties
filterPropertyDescriptorsForDependencyCheck
filterPropertyDescriptorsForDependencyCheck
isExcludedFromDependencyCheck
checkDependencies
applyPropertyValues
convertForProperty
initializeBean
invokeAwareMethods
invokeInitMethods
invokeCustomInitMethod
setInstantiationStrategy
getInstantiationStrategy
instantiationStrategy
setParameterNameDiscoverer
getParameterNameDiscoverer
parameterNameDiscoverer
setAllowCircularReferences
allowCircularReferences
setAllowRawInjectionDespiteWrapping
allowRawInjectionDespiteWrapping
getLogger
ignoredDependencyTypes
ignoredDependencyInterfaces
currentlyCreatedBean
factoryBeanInstanceCache
filteredPropertyDescriptorsCache
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ DefaultListableBeanFactory ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
DefaultListableBeanFactory 是 AbstractAutowireCapableBeanFactory 还要重的 实现类; 1473行代码。
签名是:
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
主要的私有的属性是:
@Nullable
private static Class<?> javaxInjectProviderClass;
private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories;
@Nullable
private String serializationId;
private boolean allowBeanDefinitionOverriding = true;
private boolean allowEagerClassLoading = true;
@Nullable
private Comparator<Object> dependencyComparator;
private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap(16);
private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap(256);
private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap(64);
private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap(64);
private volatile List<String> beanDefinitionNames = new ArrayList(256);
private volatile Set<String> manualSingletonNames = new LinkedHashSet(16);
@Nullable
private volatile String[] frozenBeanDefinitionNames;
private volatile boolean configurationFrozen = false;
...
}
比较重要的是 autowireCandidateResolver resolvableDependencies beanDefinitionMap(beanDefinitionMap 在这里才出现, 也算是 等到了你) ,实现了很多直接操作 BeanDefinition的方法。它实现了所有的 上面的 bf,可以说是非常的完备了!它所有方法都不是 抽象的。可以拿来就用。 但是我们会发现,它还是不够方便, 比如你自己去手动的 registerBeanDefinition ? public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
这个涉及到 BeanDefinition 的获取,这个是 后话,涉及到 xml、javaconfig配置,也就是 XmlBeanFactory,等等
———— 为什么名字是 DefaultListableBeanFactory, 而不是 DefaultBeanFactory ?listable表明了可列举,那 指的是什么 可列举?bd吗,bean name吗,bean实例吗?不太好理解。
support.DefaultListableBeanFactory
FactoryAwareOrderSourceProvider
FactoryAwareOrderSourceProvider#getOrderSource
FactoryAwareOrderSourceProvider#FactoryAwareOrderSourceProvider
FactoryAwareOrderSourceProvider#getRootBeanDefinition
FactoryAwareOrderSourceProvider#instancesToBeanNames
Jsr330ProviderFactory
Jsr330ProviderFactory#Jsr330ProviderFactory
Jsr330ProviderFactory#createDependencyProvider
Jsr330DependencyProvider
Jsr330DependencyProvider#Jsr330DependencyProvider
Jsr330DependencyProvider#get
DependencyObjectProvider
DependencyObjectProvider#getObject()
DependencyObjectProvider#getObject(java.lang.Object...)
DependencyObjectProvider#getIfAvailable
DependencyObjectProvider#getIfUnique
DependencyObjectProvider#DependencyObjectProvider
DependencyObjectProvider#getValue
DependencyObjectProvider#descriptor
DependencyObjectProvider#optional
DependencyObjectProvider#beanName
MultiElementDescriptor
MultiElementDescriptor#MultiElementDescriptor
NestedDependencyDescriptor
NestedDependencyDescriptor#NestedDependencyDescriptor
SerializedBeanFactoryReference
SerializedBeanFactoryReference#SerializedBeanFactoryReference
SerializedBeanFactoryReference#readResolve
SerializedBeanFactoryReference#id
null
copyConfigurationFrom
destroySingletons
getBean(java.lang.Class<T>)
getBean(java.lang.Class<T>, java.lang.Object...)
containsBeanDefinition
getBeanNamesForType(org.springframework.core.ResolvableType)
getBeanNamesForType(java.lang.Class<?>)
getBeanNamesForType(java.lang.Class<?>, boolean, boolean)
getBeansOfType(java.lang.Class<T>)
getBeansOfType(java.lang.Class<T>, boolean, boolean)
getBeanNamesForAnnotation
getBeansWithAnnotation
findAnnotationOnBean
registerBeanDefinition
removeBeanDefinition
getBeanDefinitionCount
getBeanDefinitionNames
registerResolvableDependency
isAutowireCandidate(java.lang.String, config.DependencyDescriptor)
getBeanDefinition
clearMetadataCache
freezeConfiguration
preInstantiateSingletons
getBeanNamesIterator
isConfigurationFrozen
isBeanEligibleForMetadataCaching
allowAliasOverriding
registerSingleton
destroySingleton
resolveNamedBean(java.lang.Class<T>)
resolveDependency
toString
DefaultListableBeanFactory()
DefaultListableBeanFactory(BeanFactory)
doGetBeanNamesForType
requiresEagerInitForType
isAutowireCandidate(java.lang.String, config.DependencyDescriptor, support.AutowireCandidateResolver)
isAutowireCandidate(java.lang.String, support.RootBeanDefinition, config.DependencyDescriptor, support.AutowireCandidateResolver)
resetBeanDefinition
clearByTypeCache
resolveNamedBean(java.lang.Class<T>, java.lang.Object...)
doResolveDependency
resolveMultipleBeans
isRequired
indicatesMultipleBeans
adaptDependencyComparator
createFactoryAwareOrderSourceProvider
findAutowireCandidates
addCandidateEntry
determineAutowireCandidate
determinePrimaryCandidate
determineHighestPriorityCandidate
isPrimary
getPriority
matchesBeanName
isSelfReference
raiseNoMatchingBeanFound
checkBeanNotOfRequiredType
createOptionalDependency
readObject
writeReplace
setSerializationId
getSerializationId
serializationId
setAllowBeanDefinitionOverriding
isAllowBeanDefinitionOverriding
allowBeanDefinitionOverriding
setAllowEagerClassLoading
isAllowEagerClassLoading
allowEagerClassLoading
setDependencyComparator
getDependencyComparator
dependencyComparator
setAutowireCandidateResolver
getAutowireCandidateResolver
autowireCandidateResolver
javaxInjectProviderClass
serializableFactories
resolvableDependencies
beanDefinitionMap
allBeanNamesByType
singletonBeanNamesByType
beanDefinitionNames
manualSingletonNames
frozenBeanDefinitionNames
configurationFrozen
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ XmlBeanFactory ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
XmlBeanFactory 是 DefaultListableBeanFactory 的子类,唯一的子类。可想而知,主要提供了xml 配置文件的方式设置 bd。。
———— 为什么 DefaultListableBeanFactory 只有一个子类? javaconfig、annotation 那一套呢?那就是 AnnotationConfigApplicationContext , 为什么没有 AnnotationConfig bf 呢?
public class XmlBeanFactory extends DefaultListableBeanFactory {
private final XmlBeanDefinitionReader reader;
public XmlBeanFactory(Resource resource) throws BeansException {
this(resource, (BeanFactory)null);
}
public XmlBeanFactory(Resource resource, BeanFactory parentBeanFactory) throws BeansException {
super(parentBeanFactory);
this.reader = new XmlBeanDefinitionReader(this);
this.reader.loadBeanDefinitions(resource);
}
}
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 其他 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// AliasRegistry SingletonBeanRegistry SimpleAliasRegistry DefaultSingletonBeanRegistry FactoryBeanRegistrySupport 就不说了,主要解决 注册、循环依赖的问题;
小结
总的来说,这个设计和实现还是相当的不错的, 可能还有小瑕疵,但基本上是尽善尽美了 !
bf 提供了完全虚拟的 aoc 容器基础, 完全不涉及到具体的 bd来源。
除了循环依赖、scope 之外 难理解之外,其他还好。比起其他的,比如 ac 简单很多。