DefaultListableBeanFactory 类继承分析
AbstractBeanFactory
- 实现了ConfigurableBeanFactory接口
- 继承FactoryBeanRegistrySupport
ConfigurableBeanFactory结构
ConfigurableBeanFactory继承了HierarchicalBeanFactory 和SingletonBeanRegistry接口。这里有个疑问,为什么AbstractFactory已经继承FactoryBeanRegistrySupport,其实已经实现了SingletonBeanRegistry接口。为什么 这里还要实现一次呢??
其实我们分开来理解就行,因为ConfigurableBeanFactory 是一个完整的接口,他需要和SingletonBeanRegistry接口一起构成一个完整的功能。所以AbstractBeanFactory要实现ConfigurableBeanFactory 接口,要么自己不全SingletonBeanRegistry接口的实现,但是这里它选择继承一个已经实现了SingletonBeanRegistry接口的类FactoryBeanRegistrySupport。这是一种很好的设计技巧 指的我们学习。
1.属性分析
- parentBeanFactory
- beanExpressionResolver :spring el解析
- conversionService
- propertyEditorRegistrars:set类型 ,用于注册propertyEditor,在
- customEditors 另外一个配置propertyEditor的地方,调用registerCustomEditor方法
- TypeConverter :覆盖propertyEditor的转换
- embeddedValueResolvers :String resolvers to apply e.g. to annotation attribute values
- beanPostProcessors:list
- hasInstantiationAwareBeanPostProcessors:表示是否注册过任何的InstantiationAwareBeanPostProcessors(应该是用来给bean 初始化Aware接口的)
- hasDestructionAwareBeanPostProcessors:是否注册过销毁Aware接口的DestructionAwareBeanPostProcessors
- scopes :类型LinkedHashMap(应该是为了保持添加的顺序)存储id 到scope对象的映射,
- securityContextProvider:Security context used when running with a SecurityManager
- mergedBeanDefinitions:Map from bean name to merged RootBeanDefinition
- alreadyCreated:set类型,存储是否创建过该bean name。
- prototypesCurrentlyInCreation: 线程局部变量存储该线程下正在创建的prototype的 bean
2.接口说明
这里需要说明的是ConfigurableBeanFactory接口 已经继承了Beanfactory接口,所以getBean方法也有了实现。
3. getBean方法分析
有四个getBean方法 都是调用doGetBean方法来获取bean的。
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
//name 转换为beanName 将&前缀去掉,并且名称规范化,将alias 转化为原名称
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
//因为singleton对象可以直接注册到 DefaultSingletonBeanRegistry 不用经过mbd
//调用DefaultSingletonBeanRegistry的getSingleton方法,前面分析过该方法就是按顺序从singtonObjects,earlySingletonObjects, singletonFactories 获取。
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
//判断是否是factorybean类型 是返回Factorybean 本身还是 调用getCachedObjectForFactoryBean 得到真实的boject 从这里可以看出 factorybean 在容器中存放的还是自己,
//在这里是判断是否需要根据条件调用它的getObject 返回 内部对象。
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
//说明prototype如果正在创建是不允许拿到的,对于prototype 对象也没有提早暴漏一说
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
//如果本factory有 则不会去找parent factory
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//避免重复创建 bean
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
//校验很简单 只检查了BeanDefinition是否是abstract类型
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);
getBean(dep);
}
}
// Create bean instance.
//这里依次处理了singleton prototype 和其他score 的获取bean操作
if (mbd.isSingleton()) {
//进入单例获取 ,循环依赖也开始工作了。
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
//这个方法 和前面一样检查factorybean类型的
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
//该方法是一个抽象 实现在AbstractAutowireCapableBeanFactory
//解决循环也在该实现内
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
下面主要针对singleton 创建分析
上图可以看出创建一个bean 开始于getSingleton(beanName,ObjectFactory)方法:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "'beanName' must not be null");
synchronized (this.singletonObjects) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<Exception>();
}
try {
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
catch (IllegalStateException ex) {
// Has the singleton object implicitly appeared in the meantime ->
// if yes, proceed with it since the exception indicates that state.
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
throw ex;
}
}
catch (BeanCreationException ex) {
if (recordSuppressedExceptions) {
for (Exception suppressedException : this.suppressedExceptions) {
ex.addRelatedCause(suppressedException);
}
}
throw ex;
}
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
afterSingletonCreation(beanName);
}
if (newSingleton) {
addSingleton(beanName, singletonObject);
}
}
return (singletonObject != NULL_OBJECT ? singletonObject : null);
}
}
说明:
前提:参数objectfactory传的的是一个内部类 zhuyao 第用了createBean方法。
1)先从singletonObjects获取,按照我们的分析第一次是空的
2)beforeSingletonCreation方法主要校验 beanName是否是排除singletonsCurrentlyInCreation,然后确认加入到singletonsCurrentlyInCreation中。
3)调用objectfactory创建
3_1)其实调用的是AbstractAutowireCapableBeanFactory#createBean=>AbstractAutowireCapableBeanFactory#doCreateBean
3_2)通过beanName和beanDefinition创建BeanWrapper
3_3)applyMergedBeanDefinitionPostProcessors 应用mbd的后处理。
3_4)检查当前bean是否正在创建 (我们得到earlySingletonExposure =true)
3_5)调用addSingletonFactory,主要singletonFactories添加objectfactory实例(这里是另外一个内部类了),删除earlySingletonObjects中的beanName ,registeredSingletons添加beanName
3_6)调用populateBean去创建改bean的依赖。
3_7_1)如果该类没有被循环应用: 调用getSingleton(beanName,false)方法,这里传入false是因为 自己拿自己不用提前暴漏的应用,所以结果还是null 这时候就正常流程走玩就行
3_7_2)如果有该bean依赖的beanother 又循环依赖bean。所以前面 3_5)中添加bojectfactory会被调用,其实调用了getEarlyBeanReference方法,调用完成后,会在earlySingletonObjects放bean ,然后删除singletonFactories中的beanname
3_7_2_1)getEarlyBeanReference 中对SmartInstantiationAwareBeanPostProcessor
对bean应用getEarlyBeanReference方法后返回 ,上面说过earlySingletonObjects已经有bean name
4)afterSingletonCreation移除 singletonsCurrentlyInCreation中的当前bean
5)addSingleton 添加到singletonObjects和registeredSingletons;移除singletonFactories和earlySingletonObjects
这里需要Objectfactory干什么呢,因为创建逻辑比较发杂。
AbstractAutowireCapableBeanFactory
AbstractAutowireCapableBeanFactory上面已经分析了部分,它实现了AutowireCapableBeanFactory接口。
DefaultListableBeanFactory
DefaultListableBeanFactory实现了ConfigurableListableBeanFactory接口 和BeanDefinitionRegistry接口。
ConfigurableListableBeanFactory接口主要继承了ListableBeanFactory AutowireCapableBeanFactory ConfigurableBeanFactory接口。
除了ListableBeanFactory 没见过 其他两个都见过,那ListableBeanFactory 主要干嘛呢?
由上图可知,ListableBeanFactory 是getBeanNames等方法的定义。
XmlBeanFactory
xmlBeanfactory 实现 也不复杂,他只是提供了一个具体加载beandefinitions的方式,而真实的加载工作又委托给XmlBeanDefinitionReader。
其他说明
BeanpostProcessor的注册
xmlbeanfactory 不会检测容器内的bean自动注册,这个功能在ApplicationContext 才会提供。
所以xmlbeanfactory没有aop功能 和事务功能。
beanpostprocesser调用逻辑: