Spring源码分析-beanFactory

AliasRegistry:定义了对别名的简单增删改操作

public interface AliasRegistry {
    void registerAlias(String var1, String var2);

    void removeAlias(String var1);

    boolean isAlias(String var1);

    String[] getAliases(String var1);
}

SimpleAliasRegistry:使用ConcurrentHashMap实现了AliasRegistry接口:

public class SimpleAliasRegistry implements AliasRegistry {
    private final Map<String, String> aliasMap = new ConcurrentHashMap(16);

    public SimpleAliasRegistry() {
    }
    ...
  }

SingletonBeanRegistry :定义对单例的注册及获取

public interface SingletonBeanRegistry {
    void registerSingleton(String var1, Object var2);

    Object getSingleton(String var1);

    boolean containsSingleton(String var1);

    String[] getSingletonNames();

    int getSingletonCount();
}

DefaultSingletonBeanRegistry:对SingletonBeanRegistry 接口的实现,同时继承了SimpleAliasRegistry 类。

public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
 protected static final Object NULL_OBJECT = new Object();//静态不可变对象Object,因为ConcurrentHashMap不能保存null值。
    private final Set<String> singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap(16));//根据map生成对应结构的set,保存正在创建的单例beanName的set
     private final Map<String, Object> singletonObjects = new ConcurrentHashMap(64);//保存单例的map
      private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap(16);//保存单例bean
              private final Map<String, Object> earlySingletonObjects = new HashMap(16);//缓存从ObjectFactory中获取的bean
                  private final Set<String> registeredSingletons = new LinkedHashSet(64);//保存已经注册的beanName,
     private boolean singletonsCurrentlyInDestruction = false;//目前是否在销毁单例
         private final Map<String, Object> disposableBeans = new LinkedHashMap();//保存只使用一次的bean
    private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap(16);//bean的包含关系
    private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap(64);//bean的依赖关系
    private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap(64);//bean的依赖关系
    //单例注册的实现
      public void registerSingleton(String beanName, Object singletonObject) throws IllegalStateException {
        Assert.notNull(beanName, "\'beanName\' must not be null");
        Map var3 = this.singletonObjects;
        synchronized(this.singletonObjects) {//对保存单例的map加锁
            Object oldObject = this.singletonObjects.get(beanName);//查看对应名字的单例是否存在
            if(oldObject != null) {//已经存在,抛出异常
                throw new IllegalStateException("Could not register object [" + singletonObject + "] under bean name \'" + beanName + "\': there is already object [" + oldObject + "] bound");
            } else {//不存在,增加这个单例对象
                this.addSingleton(beanName, singletonObject);
            }
        }
    }
    //往singletonObjects里面增加单例
       protected void addSingleton(String beanName, Object singletonObject) {
        Map var3 = this.singletonObjects;
        synchronized(this.singletonObjects) {//加锁
            this.singletonObjects.put(beanName, singletonObject != null?singletonObject:NULL_OBJECT);//待增加的singletonObject 为null则增加静态不可变类NULL_OBJECT
            this.singletonFactories.remove(beanName);//从ObjectFactory中移除beanName
            this.earlySingletonObjects.remove(beanName);//从earlySingletonObjects中移除beanName
            this.registeredSingletons.add(beanName);//将beanName保存到保存已经注册的set中
        }
    }
//增加对象工厂(工厂bean)
    protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
        Assert.notNull(singletonFactory, "Singleton factory must not be null");
        Map var3 = this.singletonObjects;
        synchronized(this.singletonObjects) {//加锁
        //判断singletonObjects是否包含这个beanName
            if(!this.singletonObjects.containsKey(beanName)) {
                this.singletonFactories.put(beanName, singletonFactory);
                this.earlySingletonObjects.remove(beanName);
                this.registeredSingletons.add(beanName);//保存beanName到set中
            }

        }
    }
//获取单例,
    public Object getSingleton(String beanName) {
    //获取单例,允许从ObjectFactory中获取
        return this.getSingleton(beanName, true);
    }
//先从保存bean对map中获取,没有获取到,则从缓存ObjectFactory获取的bean的map中获取,没有获取到,则从工厂bean获取
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        Object singletonObject = this.singletonObjects.get(beanName);
        //保存单例的map中没有获取到单例, 
         if(singletonObject == null && this.isSingletonCurrentlyInCreation(beanName)) {
            Map var4 = this.singletonObjects;
            //对单例map进行加锁
            synchronized(this.singletonObjects) {
            //从缓存ObjectFactory获取的bean的map中获取
                            singletonObject = this.earlySingletonObjects.get(beanName);
                //从ObjectFactory获取
                                if(singletonObject == null && allowEarlyReference) {
                    ObjectFactory singletonFactory = (ObjectFactory)this.singletonFactories.get(beanName);
                    if(singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);//将正在创建的bean放到早期引用map中
                        this.singletonFactories.remove(beanName);//从保存共产bean的map中移除这个beanName

                    }
                }
            }
        }

        return singletonObject != NULL_OBJECT?singletonObject:null;
    }
}

总结bean的增加和获取:
把bean增加到singletonObjects中,从singletonFactories中移除,从earlySingletonObjects中移除,再保存到registeredSingletons中。
BeanFactory:bean的获取和bean的各种属性

public interface BeanFactory {
    String FACTORY_BEAN_PREFIX = "&";

    Object getBean(String var1) throws BeansException;

    <T> T getBean(String var1, Class<T> var2) throws BeansException;

    <T> T getBean(Class<T> var1) throws BeansException;

    Object getBean(String var1, Object... var2) 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, Class<?> var2) throws NoSuchBeanDefinitionException;

    Class<?> getType(String var1) throws NoSuchBeanDefinitionException;

    String[] getAliases(String var1);
}

HierarchicalBeanFactory :在BeanFactory 的基础上增加工厂层次关系,

public interface HierarchicalBeanFactory extends BeanFactory {
    BeanFactory getParentBeanFactory();

    boolean containsLocalBean(String var1);
}

BeanDefinitionRegistry :对BeanDefinition的增删改操作

public interface BeanDefinitionRegistry extends AliasRegistry {
    void registerBeanDefinition(String var1, BeanDefinition var2) throws BeanDefinitionStoreException;

    void removeBeanDefinition(String var1) throws NoSuchBeanDefinitionException;

    BeanDefinition getBeanDefinition(String var1) throws NoSuchBeanDefinitionException;

    boolean containsBeanDefinition(String var1);

    String[] getBeanDefinitionNames();

    int getBeanDefinitionCount();

    boolean isBeanNameInUse(String var1);
}

FactoryBeanRegistrySupport :增加对FactoryBean的操作

public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry { 
private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap(16);//缓存从工厂bean中获取的对象

}

ConfigurableBeanFactory :提供配置Factory的各种方法

public interface ConfigurableBeanFactory extends HierarchicalBeanFactory, SingletonBeanRegistry {
//bean的属性
   String SCOPE_SINGLETON = "singleton";
    String SCOPE_PROTOTYPE = "prototype";
      void setParentBeanFactory(BeanFactory var1) throws IllegalStateException;//设置父工厂
      void setBeanClassLoader(ClassLoader var1);//设置bean的类加载器
      void setBeanExpressionResolver(BeanExpressionResolver var1);//设置bean表达式解析器
      void setConversionService(ConversionService var1);//设置类型转换器
      void addPropertyEditorRegistrar(PropertyEditorRegistrar var1);// 用一个属性编辑注册器(PropertyEditorRegistry)注册一个自定义的属性编辑器(PropertyEditor)的策略接口。
      void setTypeConverter(TypeConverter var1);//设置类型转换器
      void addBeanPostProcessor(BeanPostProcessor var1);//增加bean后处理器
      ...
}

ListableBeanFactory :根据各种条件获取bean

public interface ListableBeanFactory extends BeanFactory {
<T> Map<String, T> getBeansOfType(Class<T> var1) throws BeansException;//根据类型获取bean
    ...
}

AbstractBeanFactory :继承了FactoryBeanRegistrySupport ,同时实现ConfigurableBeanFactory 接口的方法

public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
     private BeanFactory parentBeanFactory;//父beanFactory
    private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();//获取类加载器,首选当前线程的类加载器
    private ClassLoader tempClassLoader;//临时类加载器
    private boolean cacheBeanMetadata = true;
    private BeanExpressionResolver beanExpressionResolver;
    private ConversionService conversionService;
    private final Set<PropertyEditorRegistrar> propertyEditorRegistrars = new LinkedHashSet(4);
    private TypeConverter typeConverter;
    private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap(4);
    private final List<StringValueResolver> embeddedValueResolvers = new LinkedList();
    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList();//bean后处理器
    private boolean hasInstantiationAwareBeanPostProcessors;
    private boolean hasDestructionAwareBeanPostProcessors;
    private final Map<String, Scope> scopes = new HashMap(8);
    private SecurityContextProvider securityContextProvider;
    private final Map<String, RootBeanDefinition> mergedBeanDefinitions = new ConcurrentHashMap(64);
    private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap(64));
    private final ThreadLocal<Object> prototypesCurrentlyInCreation = new NamedThreadLocal("Prototype beans currently in creation");
//构造方法设置父BeanFactory 
public AbstractBeanFactory(BeanFactory parentBeanFactory) {
        this.parentBeanFactory = parentBeanFactory;
    }
     public Object getBean(String name) throws BeansException {
        return this.doGetBean(name, (Class)null, (Object[])null, false);
    }

    public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
        return this.doGetBean(name, requiredType, (Object[])null, false);
    }
//一系列最核心的getBean方法。非常重要!
    public Object getBean(String name, Object... args) throws BeansException {
        return this.doGetBean(name, (Class)null, args, false);
    }

    public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
        return this.doGetBean(name, requiredType, args, false);
    }
    //获取bean
    protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly) throws BeansException {
        final String beanName = this.transformedBeanName(name);//装换beanName
        Object sharedInstance = this.getSingleton(beanName);//调用父类方法获取beanName对应单例,尝试直接从缓存获取获取singletonFactories中的ObjectFactory中获取
        Object bean;
        if(sharedInstance != null && args == null) {
            if(this.logger.isDebugEnabled()) {
                if(this.isSingletonCurrentlyInCreation(beanName)) {
                    this.logger.debug("Returning eagerly cached instance of singleton bean \'" + beanName + "\' that is not fully initialized yet - a consequence of a circular reference");
                } else {
                    this.logger.debug("Returning cached instance of singleton bean \'" + beanName + "\'");
                }
            }

            bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, (RootBeanDefinition)null);//bean的实例化,如果是工厂bean,则获取工厂bean的里面的bean
        } else {
            if(this.isPrototypeCurrentlyInCreation(beanName)) {
                throw new BeanCurrentlyInCreationException(beanName);
            }

            BeanFactory ex = this.getParentBeanFactory();
            if(ex != null && !this.containsBeanDefinition(beanName)) {
                String var24 = this.originalBeanName(name);
                if(args != null) {
                    return ex.getBean(var24, args);
                }

                return ex.getBean(var24, requiredType);
            }

            if(!typeCheckOnly) {
                this.markBeanAsCreated(beanName);
            }

            try {
                final RootBeanDefinition ex1 = this.getMergedLocalBeanDefinition(beanName);
                this.checkMergedBeanDefinition(ex1, beanName, args);
                String[] dependsOn = ex1.getDependsOn();
                String[] scopeName;
                if(dependsOn != null) {
                    scopeName = dependsOn;
                    int scope = dependsOn.length;

                    for(int ex2 = 0; ex2 < scope; ++ex2) {
                        String dependsOnBean = scopeName[ex2];
                        if(this.isDependent(beanName, dependsOnBean)) {
                            throw new BeanCreationException(ex1.getResourceDescription(), beanName, "Circular depends-on relationship between \'" + beanName + "\' and \'" + dependsOnBean + "\'");
                        }

                        this.registerDependentBean(dependsOnBean, beanName);
                        this.getBean(dependsOnBean);
                    }
                }

                if(ex1.isSingleton()) {
                    sharedInstance = this.getSingleton(beanName, new ObjectFactory() {
                        public Object getObject() throws BeansException {
                            try {
                                return AbstractBeanFactory.this.createBean(beanName, ex1, args);
                            } catch (BeansException var2) {
                                AbstractBeanFactory.this.destroySingleton(beanName);
                                throw var2;
                            }
                        }
                    });
                    bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, ex1);
                } else if(ex1.isPrototype()) {
                    scopeName = null;

                    Object var25;
                    try {
                        this.beforePrototypeCreation(beanName);
                        var25 = this.createBean(beanName, ex1, args);
                    } finally {
                        this.afterPrototypeCreation(beanName);
                    }

                    bean = this.getObjectForBeanInstance(var25, name, beanName, ex1);
                } else {
                    String var26 = ex1.getScope();
                    Scope var27 = (Scope)this.scopes.get(var26);
                    if(var27 == null) {
                        throw new IllegalStateException("No Scope registered for scope \'" + var26 + "\'");
                    }

                    try {
                        Object var28 = var27.get(beanName, new ObjectFactory() {
                            public Object getObject() throws BeansException {
                                AbstractBeanFactory.this.beforePrototypeCreation(beanName);

                                Object var1;
                                try {
                                    var1 = AbstractBeanFactory.this.createBean(beanName, ex1, args);
                                } finally {
                                    AbstractBeanFactory.this.afterPrototypeCreation(beanName);
                                }

                                return var1;
                            }
                        });
                        bean = this.getObjectForBeanInstance(var28, name, beanName, ex1);
                    } catch (IllegalStateException var21) {
                        throw new BeanCreationException(beanName, "Scope \'" + var26 + "\' 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", var21);
                    }
                }
            } catch (BeansException var23) {
                this.cleanupAfterBeanCreationFailure(beanName);
                throw var23;
            }
        }
}

AutowireCapableBeanFactory:提供创建bean,自动注入,初始化以及应用bean的后处理器

public interface AutowireCapableBeanFactory extends BeanFactory {
   <T> T createBean(Class<T> var1) throws BeansException;

    void autowireBean(Object var1) throws BeansException;
    ...
}

AbstractAutowireCapableBeanFactory :继承AbstractBeanFactory ,实现AutowireCapableBeanFactory 接口

//创建bean的实现
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {   public <T> T createBean(Class<T> beanClass) throws BeansException {
        RootBeanDefinition bd = new RootBeanDefinition(beanClass);
        bd.setScope("prototype");
        bd.allowCaching = ClassUtils.isCacheSafe(beanClass, this.getBeanClassLoader());
        return this.createBean(beanClass.getName(), bd, (Object[])null);
    }

}

DefaultListableBeanFactory:综合上面所有功能,主要是对bean注册后的处理

    原文作者:Spring MVC
    原文地址: https://blog.csdn.net/u011545613/article/details/77145590
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞