spring源码核心:DefaultListableBeanFactory

Posted ppjj

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring源码核心:DefaultListableBeanFactory相关的知识,希望对你有一定的参考价值。

本文转自:https://my.oschina.net/u/2246410/blog/1801293/

核心创建方式

Class<?> ob = Class.forName("com.fxl.spring.test.SayServiceImpl");
    //ob.getDeclaredConstructor(); 检测构造器是否是公有
    SayService say = (SayService) ob.newInstance();
    say.getMessage();

结构图

 

 

 

接口:
  • AliasRegistry:注册别名和具体的名称接口
  • SingletonBeanRegistry:注册bean的接口
  • BeanFactorybean的实际调用接口
  • HierarchicalBeanFactorybeanfactory的强化接口
  • ConfigurableBeanFactory:beanfactory的调用接口
  • AutowireCapableBeanFactorybeanfactory的强化接口
  • ListableBeanFactorybeanfactory的强化接口,批量处理bean
  • BeanDefinitionRegistry:bean的调用接口,包括接口别名
  • ConfigurableListableBeanFactory:除了可配置beanfactory之外,它还提供了用于分析和修改bean定义的工具,以及预实例化单例
实现类
  • SimpleAliasRegistry:存放别名和实际
  • public class SimpleAliasRegistry implements AliasRegistry {
    
        /** Map from alias to canonical name */
        private final Map<String, String> aliasMap = new ConcurrentHashMap<String, String>(16);
    }

    DefaultSingletonBeanRegistry:存放具体的bean

    • singletonObjects: 存放bean的名称及实例
    • singletonFactories: 存放bean的名称及实例创建工厂
    • public class DefaultSingletonBeanRegistry extends SimpleAliasRegistry implements SingletonBeanRegistry {
      
          /**
           * Internal marker for a null singleton object:
           * used as marker value for concurrent Maps (which don\'t support null values).
           */
          protected static final Object NULL_OBJECT = new Object();
      
      
          /** Logger available to subclasses */
          protected final Log logger = LogFactory.getLog(getClass());
      
          /** Cache of singleton objects: bean name --> bean instance */
          // bean的名称和实例
          private final Map<String, Object> \'singletonObjects\' = new ConcurrentHashMap<String, Object>(64);
      
          /** Cache of singleton factories: bean name --> ObjectFactory */
          // bean名称和产生的工厂
          private final Map<String, ObjectFactory<?>> singletonFactories = new HashMap<String, ObjectFactory<?>>(16);
      
          /** Cache of early singleton objects: bean name --> bean instance */
          // 早期存放bean的名称和实例
          private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);
      
          /** Set of registered singletons, containing the bean names in registration order */
          // bean的名称
          private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);
      
          /** Names of beans that are currently in creation */
          // 创建的类
          private final Set<String> singletonsCurrentlyInCreation =
                  Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
      
          /** Names of beans currently excluded from in creation checks */
          // 当前创建时需要排除的名称
          private final Set<String> inCreationCheckExclusions =
                  Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(16));
      
          /** List of suppressed Exceptions, available for associating related causes */
          // 抛出的错误
          private Set<Exception> suppressedExceptions;
      
          /** Flag that indicates whether we\'re currently within destroySingletons */
          // 销毁时的状态
          private boolean singletonsCurrentlyInDestruction = false;
      
          /** Disposable bean instances: bean name --> disposable instance */
          // bean名称
          private final Map<String, Object> disposableBeans = new LinkedHashMap<String, Object>();
      
          /** Map between containing bean names: bean name --> Set of bean names that the bean contains */
          // 名称
          private final Map<String, Set<String>> containedBeanMap = new ConcurrentHashMap<String, Set<String>>(16);
      
          /** Map between dependent bean names: bean name --> Set of dependent bean names */
          // 依赖的名称
          private final Map<String, Set<String>> dependentBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
      
          /** Map between depending bean names: bean name --> Set of bean names for the bean\'s dependencies */
          // 依赖的名称
          private final Map<String, Set<String>> dependenciesForBeanMap = new ConcurrentHashMap<String, Set<String>>(64);
      }
      • FactoryBeanRegistrySupport:bean缓存
      • public abstract class FactoryBeanRegistrySupport extends DefaultSingletonBeanRegistry {
        
            /** Cache of singleton objects created by FactoryBeans: FactoryBean name --> object */
            // 由FactoryBean创建的单例对象的缓存:FactoryBean名称—对象
            private final Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<String, Object>(16);
        }
        • AbstractBeanFactory
        • public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
          
              /** Parent bean factory, for bean inheritance support */
              // 父类 bean factory
              private BeanFactory parentBeanFactory;
          
              /** ClassLoader to resolve bean class names with, if necessary */
              // 类加载器
              private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
          
              /** ClassLoader to temporarily resolve bean class names with, if necessary */
              // 类加载器在必要时临时解析bean类名
              private ClassLoader tempClassLoader;
          
              /** Whether to cache bean metadata or rather reobtain it for every access */
              // 是否缓存bean元数据,或者是否为每个访问重新获取它
              private boolean cacheBeanMetadata = true;
          
              /** Resolution strategy for expressions in bean definition values */
              //  bean定义值的表达式的解析策略
              private BeanExpressionResolver beanExpressionResolver;
          
              /** Spring ConversionService to use instead of PropertyEditors */
              // 使用Spring ConversionService来代替属性编辑器
              private ConversionService conversionService;
          
              /** Custom PropertyEditorRegistrars to apply to the beans of this factory */
              // 自定义propertyeditorregistry应用到该工厂的bean
              private final Set<PropertyEditorRegistrar> propertyEditorRegistrars =
                      new LinkedHashSet<PropertyEditorRegistrar>(4);
          
              /** A custom TypeConverter to use, overriding the default PropertyEditor mechanism */
              // 用于使用的自定义类型转换,覆盖默认的PropertyEditor机制
              private TypeConverter typeConverter;
          
              /** Custom PropertyEditors to apply to the beans of this factory */
              // 自定义属性编辑器应用到该工厂的bean
              private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors =
                      new HashMap<Class<?>, Class<? extends PropertyEditor>>(4);
          
              /** String resolvers to apply e.g. to annotation attribute values */
              // 将字符串解析器应用于注释属性值
              private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>();
          
              /** BeanPostProcessors to apply in createBean */
              // 用于在createBean中应用的beanpost处理器
              private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
          
              /** Indicates whether any InstantiationAwareBeanPostProcessors have been registered */
              // 表明InstantiationAwareBeanPostProcessors是否已经注册
              private boolean hasInstantiationAwareBeanPostProcessors;
          
              /** Indicates whether any DestructionAwareBeanPostProcessors have been registered */
              // 表明DestructionAwareBeanPostProcessors是否已经注册
              private boolean hasDestructionAwareBeanPostProcessors;
          
              /** Map from scope identifier String to corresponding Scope */
              // 从范围标识符字符串映射到对应的范围
              private final Map<String, Scope> scopes = new HashMap<String, Scope>(8);
          
              /** Security context used when running with a SecurityManager */
              // 与安全管理器一起运行时使用的安全上下文
              private SecurityContextProvider securityContextProvider;
          
              /** Map from bean name to merged RootBeanDefinition */
              // 从bean名称映射到合并的RootBeanDefinition
              private final Map<String, RootBeanDefinition> mergedBeanDefinitions =
                      new ConcurrentHashMap<String, RootBeanDefinition>(64);
          
              /** Names of beans that have already been created at least once */
              // 已经至少创建过一次的bean的名称
              private final Set<String> alreadyCreated = Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(64));
          
              /** Names of beans that are currently in creation */
              // 当前正在创建的bean的名称
              private final ThreadLocal<Object> prototypesCurrentlyInCreation =
                      new NamedThreadLocal<Object>("Prototype beans currently in creation");
          }

          AbstractAutowireCapableBeanFactory:抽象bean工厂超类,实现了默认bean的创建,具有由RootBeanDefinition类指定的全部功能

          • 提供bean创建(使用构造函数解析)、属性填充、连接(包括自动连接)和初始化。处理运行时bean引用、解析托管集合、调用初始化方法等。支持自动装配构造函数、属性名和属性
          • public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
                    implements AutowireCapableBeanFactory {
            
                /** Strategy for creating bean instances */
                // 创建bean实例的策略
                private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
            
                /** Resolver strategy for method parameter names */
                // 方法参数名的解析器策略
                private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
            
                /** Whether to automatically try to resolve circular references between beans */
                // 是否自动尝试解析bean之间的循环引用
                private boolean allowCircularReferences = true;
            
                /**
                 * Whether to resort to injecting a raw bean instance in case of circular reference, even if the injected bean eventually got wrapped.
                 */
                // 是否在循环引用的情况下使用原始bean实例,即使注入的bean最终被包装了
                private boolean allowRawInjectionDespiteWrapping = false;
            
                /**
                 * Dependency types to ignore on dependency check and autowire, as Set of Class objects: for example, String. Default is none.
                 */
                 // 依赖类型忽略依赖检查和自动连接,这是类对象的集合:例如,String。默认是没有的。
                private final Set<Class<?>> ignoredDependencyTypes = new HashSet<Class<?>>();
            
                /**
                 * Dependency interfaces to ignore on dependency check and autowire, as Set of  Class objects. By default, only the BeanFactory interface is ignored.
                 */
                 // 依赖接口忽略依赖检查和自动连接,这是类对象的集合。默认情况下,只会忽略BeanFactory接口。
                private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<Class<?>>();
            
                /** Cache of unfinished FactoryBean instances: FactoryBean name --> BeanWrapper */
                // 未完成的FactoryBean实例的缓存:FactoryBean的名称—bean包装器
                private final Map<String, BeanWrapper> factoryBeanInstanceCache =
                        new ConcurrentHashMap<String, BeanWrapper>(16);
            
                /** Cache of filtered PropertyDescriptors: bean Class -> PropertyDescriptor array */
                // 过滤的属性描述符的缓存:bean类-属性描述符数组
                private final Map<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
                        new ConcurrentHashMap<Class<?>, PropertyDescriptor[]>(64);
            }
            • DefaultListableBeanFactory:在访问bean之前,典型的用法是先注册所有的bean定义(可能是从bean定义文件中读取)。因此,Bean定义查找在本地Bean定义表中是一种廉价的操作,在预先构建的Bean定义元数据对象上运行。
            • public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
                      implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
              
                  private static Class<?> javaxInjectProviderClass = null;
              
                  /** Map from serialized id to factory instance */
                  // 序列化的工程id
                  private static final Map<String, Reference<DefaultListableBeanFactory>> serializableFactories =
                          new ConcurrentHashMap<String, Reference<DefaultListableBeanFactory>>(8);
              
                  /** Optional id for this factory, for serialization purposes */
                  //这个工厂的可选id,用于序列化
                  private String serializationId;
              
                  /** Whether to allow re-registration of a different definition with the same name */
                  // 是否允许用相同的名称重新注册一个不同的定义
                  private boolean allowBeanDefinitionOverriding = true;
              
                  /** Whether to allow eager class loading even for lazy-init beans */
                  // 是否允许热加载即使是 懒加载设置
                  private boolean allowEagerClassLoading = true;
              
                  /** Optional OrderComparator for dependency Lists and arrays */
                  // 用于依赖列表和数组的可选的OrderComparator
                  private Comparator<Object> dependencyComparator;
              
                  /** Resolver to use for checking if a bean definition is an autowire candidate */
                  // 解析器用于检查bean定义是否为自动连接的候选
                  private AutowireCandidateResolver autowireCandidateResolver = new SimpleAutowireCandidateResolver();
              
                  /** Map from dependency type to corresponding autowired value */
                  // 从依赖类型映射到对应的自动连接值
                  private final Map<Class<?>, Object> resolvableDependencies = new HashMap<Class<?>, Object>(16);
              
                  /** Map of bean definition objects, keyed by bean name */
                  // bean定义对象的映射,以bean名称为键
                  private final Map<String, BeanDefinition> \'beanDefinitionMap\' = new ConcurrentHashMap<String, BeanDefinition>(64);
              
                  /** Map of singleton and non-singleton bean names keyed by dependency type */
                  // 单例和非单例bean的映射,依赖于依赖类型
                  private final Map<Class<?>, String[]> allBeanNamesByType = new ConcurrentHashMap<Class<?>, String[]>(64);
              
                  /** Map of singleton-only bean names keyed by dependency type */
                  // 依赖类型的名称
                  private final Map<Class<?>, String[]> singletonBeanNamesByType = new ConcurrentHashMap<Class<?>, String[]>(64);
              
                  /** List of bean definition names, in registration order */
                  // 默认的名称列表
                  private final List<String> beanDefinitionNames = new ArrayList<String>();
              
                  /** Whether bean definition metadata may be cached for all beans */
                  // 是否为所有bean缓存bean定义元数据
                  private boolean configurationFrozen = false;
              
                  /** Cached array of bean definition names in case of frozen configuration */
                  // 在冻结配置的情况下,缓存的bean定义名称
                  private String[] frozenBeanDefinitionNames;
              }
              beanfactory:bean的创建工厂
              • 流程:
                • AbstractApplicationContext->refresh()->finishBeanFactoryInitialization():实例化bean的时候,会调用beanFactory.preInstantiateSingletons()
                • 接着在 DefaultListableBeanFactory->preInstantiateSingletons() 实例化bean的时候,调用AbstractBeanFactory->getBean()
                • 接着在AbstractBeanFactory->doGetBean()中使用getSingleton()回调一个beanfactory
                • 最后调用 SimpleInstantiationStrategy->instantiate()的来实例化bean
                • 1. DefaultListableBeanFactory->preInstantiateSingletons():
                  public void preInstantiateSingletons() throws BeansException {
                  
                      List<String> beanNames;
                      synchronized (this.beanDefinitionMap) {
                          beanNames = new ArrayList<String>(this.beanDefinitionNames);
                      }
                      for (String beanName : beanNames) {
                          RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
                          if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                                  getBean(beanName);
                          }
                      }
                  }
                  2. AbstractBeanFactory->getBean(String beanName);
                  public Object getBean(String name) throws BeansException {
                      return doGetBean(name, null, null, false);
                  }
                  3.AbstractBeanFactory->doGetBean(String beanName);一个回调用来生成 bean
                  protected <T> T doGetBean(
                          final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
                          throws BeansException {
                      final String beanName = transformedBeanName(name);
                      Object bean;
                      ...
                      ...
                      \'getSingleton回调一个ObjectFactory\'
                      sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                          @Override
                          public Object getObject() throws BeansException {
                              try {
                                  return createBean(beanName, mbd, args);
                              }catch (BeansException ex) {
                                  destroySingleton(beanName);
                              }
                          }
                      });
                      ...
                      ...
                      bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                      return (T) bean;
                  }
                  4. DefaultSingletonBeanRegistry.class->getSingleton:调用singletonFactory的回调来实现bean的创建
                  public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
                      synchronized (this.singletonObjects) {
                          Object singletonObject = this.singletonObjects.get(beanName);
                          if (singletonObject  null) {
                              ...
                              ...
                              try {
                                  singletonObject = singletonFactory.getObject();
                              }
                              ...
                              ...
                          return (singletonObject != NULL_OBJECT ? singletonObject : null);
                      }
                  }
                  5. SimpleInstantiationStrategy->instantiate()
                  BeanDefinition: spring的bean默认映射对象
                  • 创建流程:
                    • AbstractApplicationContext->refresh():刷新context的信息。
                    • obtainFreshBeanFactory():创建beanfactory,并将xml里面的bean解析成BeanDefinition,存放到beanDefinitionMap中。
                      • 先从XmlReaderContext中读取配置,然后在根据配置BeanDefinitionDocumentReader 将BeanDefinition加载进去
                  • 分析bean
                  • private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
                        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
                            importBeanDefinitionResource(ele);
                        }
                        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
                            processAliasRegistration(ele);
                        }
                        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
                            processBeanDefinition(ele, delegate);   //加载bean
                        }
                        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
                            // recurse
                            doRegisterBeanDefinitions(ele);
                        }
                    }

                    BeanDefinitionReaderUtils工具类中的createBeanDefin

                  • public static AbstractBeanDefinition createBeanDefinition(
                                String parentName, String className, ClassLoader classLoader) throws ClassNotFoundException {
                    
                            GenericBeanDefinition bd = new GenericBeanDefinition();
                            bd.setParentName(parentName);
                            if (className != null) {
                                if (classLoader != null) {
                                    bd.setBeanClass(ClassUtils.forName(className, classLoader));
                                }
                                else {
                                    bd.setBeanClassName(className);
                                }
                            }
                            return bd;
                        }
                    • BeanDefinition的创建组成:
                    • 1. \'属性\'
                      public abstract class AttributeAccessorSupport implements AttributeAccessor, Serializable {
                      
                          /** Map with String keys and Object values */
                          private final Map<String, Object> attributes = new LinkedHashMap<String, Object>(0);
                      }
                      2. \'资源\'
                      public class BeanMetadataAttributeAccessor extends AttributeAccessorSupport implements BeanMetadataElement {
                      
                          private Object source;
                      }
                      
                      3. \'对象信息\'
                      public abstract class AbstractBeanDefinition extends BeanMetadataAttributeAccessor
                              implements BeanDefinition, Cloneable {
                      
                          public static final String SCOPE_DEFAULT = "";
                          public static final int AUTOWIRE_NO = AutowireCapableBeanFactory.AUTOWIRE_NO;
                          public static final int AUTOWIRE_BY_NAME = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME;
                          public static final int AUTOWIRE_BY_TYPE = AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE;
                          public static final int AUTOWIRE_CONSTRUCTOR = AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR;
                      
                          public static final int AUTOWIRE_AUTODETECT = AutowireCapableBeanFactory.AUTOWIRE_AUTODETECT;
                      
                          public static final int DEPENDENCY_CHECK_NONE = 0;
                          public static final int DEPENDENCY_CHECK_OBJECTS = 1;
                          public static final int DEPENDENCY_CHECK_SIMPLE = 2;
                          public static final int DEPENDENCY_CHECK_ALL = 3;
                      
                          public static final String INFER_METHOD = "(inferred)";
                      
                      
                          private volatile Object beanClass;
                      
                          private String scope = SCOPE_DEFAULT;
                      
                          private boolean abstractFlag = false;
                      
                          private boolean lazyInit = false;
                      
                          private int autowireMode = AUTOWIRE_NO;
                      
                          private int dependencyCheck = DEPENDENCY_CHECK_NONE;
                      
                          private String[] dependsOn;
                      
                          private boolean autowireCandidate = true;
                      
                          private boolean primary = false;
                      
                          private 以上是关于spring源码核心:DefaultListableBeanFactory的主要内容,如果未能解决你的问题,请参考以下文章

                      Spring源码核心剖析

                      Spring源码核心知识点凝练总结

                      深入浅出Spring原理及实战「原理分析专题」不看源码就带你剖析IOC容器核心流程以及运作原理

                      从零开始手写 spring ioc 框架,深入学习 spring 源码

                      从零开始手写 spring ioc 框架,深入学习 spring 源码

                      spring源码核心:DefaultListableBeanFactory