1. DefaultListableBeanFactory的作用:

默认实现了ListableBeanFactory和BeanDefinitionRegistry接口,基于bean definition对象,是一个成熟的bean factroy。

最典型的应用是:在访问bean前,先注册所有的definition(可能从bean definition配置文件中)。使用预先建立的bean定义元数据对象,从本地的bean definition表中查询bean definition因而将不会花费太多成本。

DefaultListableBeanFactory既可以作为一个单独的beanFactory,也可以作为自定义beanFactory的父类。

注意:特定格式bean definition的解析器可以自己实现,也可以使用原有的解析器,如:

PropertiesBeanDefinitionReader和XmLBeanDefinitionReader。

2. DefaultListableBeanFactory的继承关系

3. DefaultListableBeanFactory的父类

直接继承关系:

  1. @SuppressWarnings("serial")
  2. public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
  3. implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {

   3.1 静态方法

  1. private static Class<?> javaUtilOptionalClass = null;
  2.  
  3. private static Class<?> javaxInjectProviderClass = null;
  4.  
  5. static {
  6. try {
  7. javaUtilOptionalClass =
  8. ClassUtils.forName("java.util.Optional", DefaultListableBeanFactory.class.getClassLoader());
  9. }
  10. catch (ClassNotFoundException ex) {
  11. // Java 8 not available - Optional references simply not supported then.
  12. }
  13. try {
  14. javaxInjectProviderClass =
  15. ClassUtils.forName("javax.inject.Provider", DefaultListableBeanFactory.class.getClassLoader());
  16. }
  17. catch (ClassNotFoundException ex) {
  18. // JSR-330 API not available - Provider interface simply not supported then.
  19. }
  20. }

spring提供一些实用的综合工具类如ClassUtils,ClassUtils提供了对类的实用方法,主要用在框架内部,想要了解更全面的类的工具方法可以参考apache commons lang。

  1. Commons Lang
  2. The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods.
  3.  
  4. Lang provides a host of helper utilities for the java.lang API, notably String manipulation methods, basic numerical methods, object reflection, concurrency, creation and serialization and System properties. Additionally it contains basic enhancements to java.util.Date and a series of utilities dedicated to help with building methods, such as hashCode, toString and equals
  1. ClassUtils.forName方法是class.forname的重写,返回一个类的实例,区别请参考源码。

上述静态方法中返回了javax.inject.Provider的一个实例,那么我们揭开javax.inject.Provider的面纱看看它到底起了什么作用。更多关于inject见《javax.inject中@Inject、@Named、@Qualifier和@Provider用法

3.2 继承自AbstractAutowireCapableBeanFactory的方法:

AbstractAutowireCapableBeanFactory的作用:

提供bean的创建 (有construct方法), 属性注值, 绑定 (包括自动绑定)和初始化.

处理运行时bean引用, 解析管理的集合, 调用初始化方法。

最主要的子类要实现的模板方法是 AutowireCapableBeanFactory.resolveDependency(DependencyDescriptor, String, Set, TypeConverter), 这个方法用来实现类型的自动绑定.

在DefaultListableBeanFactory中实现了AbstractAutowireCapableBeanFactory.copyConfigurationFrom

  1. @Override
  2. public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
  3. super.copyConfigurationFrom(otherFactory);
  4. if (otherFactory instanceof DefaultListableBeanFactory) {
  5. DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory;
  6. this.allowBeanDefinitionOverriding = otherListableFactory.allowBeanDefinitionOverriding;
  7. this.allowEagerClassLoading = otherListableFactory.allowEagerClassLoading;
  8. this.autowireCandidateResolver = otherListableFactory.autowireCandidateResolver;
  9. this.resolvableDependencies.putAll(otherListableFactory.resolvableDependencies);
  10. }
  11. }

其中:

allowBeanDefinitionOverriding定义了是否允许同名的不同bean definition再次进行注册;

allowEagerClassLoading 定义了是否允许eager类(相对于lazy)的加载,甚至延迟初始化的bean的加载。

autowireCandidateResolver是一个策略接口,用来决定一个特定的bean definition 是否满足做一个特定依赖的自动绑定的候选项,方法如下所示:

  1. //SimpleAutowireCandidateResolver implements AutowireCandidateResolver
  1. @Override
  1. public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
  2. return bdHolder.getBeanDefinition().isAutowireCandidate();
  3. }
  1. //GenericTypeAwareAutowireCandidateResolver implements AutowireCandidateResolver
  1. @Override
    public boolean isAutowireCandidate(BeanDefinitionHolder bdHolder, DependencyDescriptor descriptor) {
  2. if (!bdHolder.getBeanDefinition().isAutowireCandidate()) {
  3. // if explicitly false, do not proceed with any other checks
  4. return false;
  5. }
  6. return (descriptor == null || checkGenericTypeMatch(bdHolder, descriptor));
  7. }

resolvableDependencies:定义了依赖类型和其对应的自动绑定值的键值对集合。

AbstractAutowireCapableBeanFactory的copyConfigurationFrom方法:

  1. @Override
  2. public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
  3. super.copyConfigurationFrom(otherFactory);
  4. if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
  5. AbstractAutowireCapableBeanFactory otherAutowireFactory =
  6. (AbstractAutowireCapableBeanFactory) otherFactory;
  7. this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
  8. this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
  9. this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
  10. this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
  11. }
  12. }

其中,instantiationStrategy 为创建bean 实例的策略,默认值:

private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

allowCircularReferences 确定是否自动尝试去解析循环引用的bean。

ignoredDependencyTypes 定义了在依赖检查和自动绑定时要忽略的依赖类型,是一组类对象,例如string,默认为没有。

ignoredDependencyInterfaces  定义了在依赖检查和自动绑定时要忽略的依赖接口,是一组类对象,默认情况下,只有beanFactory接口被忽略。

父类AbstractBeanFactory的copyConfigurationFrom的实现如下:

  1. @Override
  2. public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
  3. Assert.notNull(otherFactory, "BeanFactory must not be null");
  4. setBeanClassLoader(otherFactory.getBeanClassLoader());
  5. setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
  6. setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
  7. if (otherFactory instanceof AbstractBeanFactory) {
  8. AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
  9. this.customEditors.putAll(otherAbstractFactory.customEditors);
  10. this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
  11. this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
  12. this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
  13. otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
  14. this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
  15. otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
  16. this.scopes.putAll(otherAbstractFactory.scopes);
  17. this.securityContextProvider = otherAbstractFactory.securityContextProvider;
  18. }
  19. else {
  20. setTypeConverter(otherFactory.getTypeConverter());
  21. }
  22. }

其中

  1. customEditors 是自定义的属性编辑器,适用于该beanFactory的所有bean
    propertyEditorRegistrars属性编辑器的注册器,使用于该beanFactory的所有bean
  1. beanPostProcessors 创建bean时应用的beanPostProcessors
  1. hasInstantiationAwareBeanPostProcessors 表明是否注册有任何的InstantiationAwareBeanPostProcessors
    hasDestructionAwareBeanPostProcessors表明是否注册有任何的DestructionAwareBeanPostProcessors
  1. scopes:域标识符和对应域的键值对集合。
  2.  
  3. securityContextProvider 运行SecurityManager时使用的security context
  1. 3.3 继承自ListableBeanFactory接口的方法
  1. ListableBeanFactorybeanFactory接口的扩展接口,它可以枚举所有的bean实例,而不是客户端通过名称一个一个的查询得出所有的实例。要预加载所有的bean定义的beanfactory可以实现这个接口来。该 接口定义了访问容器中Bean基本信息的若干方法,如查看Bean的个数、获取某一类型Bean的配置名、查看容器中是否包括某一Bean等方法;
  1. containsBeanDefinition(String beanName)
  2. Check if this bean factory contains a bean definition with the given name.
  3.  
  4. findAnnotationOnBean(String beanName, Class<A> annotationType)
  5. Find a Annotation of annotationType on the specified bean, traversing its interfaces and super classes if no annotation can be found on the given class itself.
  6.  
  7. getBeanDefinitionCount()
  8. Return the number of beans defined in the factory.
  9.  
  10. getBeanDefinitionNames()
  11. Return the names of all beans defined in this factory.
  12.  
  13. getBeanNamesForType(Class<?> type)
  14. Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
  15.  
  16. getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
  17. Return the names of beans matching the given type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
  18.  
  19. getBeansOfType(Class<T> type)
  20. Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
  21.  
  22. getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
  23. Return the bean instances that match the given object type (including subclasses), judging from either bean definitions or the value of getObjectType in the case of FactoryBeans.
  24.  
  25. getBeansWithAnnotation(Class<? extends Annotation> annotationType)
  26. Find all beans whose Class has the supplied Annotation type.
  1. 3.4 继承自ConfigurableListableBeanFactory接口的方法
    ConfigurableListableBeanFactory 它同时继承了ListableBeanFactoryAutowireCapableBeanFactoryConfigurableBeanFactory,提供了对bean定义的分析和修改的便利方法,同时也提供了对单例的预实例化。
  1. void freezeConfiguration()
  2. Freeze all bean definitions, signalling that the registered bean definitions will not be modified or post-processed any further.
  3.  
  4. BeanDefinition getBeanDefinition(String beanName)
  5. Return the registered BeanDefinition for the specified bean, allowing access to its property values and constructor argument value (which can be modified during bean factory post-processing).
  6.  
  7. void ignoreDependencyInterface(Class<?> ifc)
  8. Ignore the given dependency interface for autowiring.
  9.  
  10. void ignoreDependencyType(Class<?> type)
  11. Ignore the given dependency type for autowiring: for example, String.
  12.  
  13. boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
  14. Determine whether the specified bean qualifies as an autowire candidate, to be injected into other beans which declare a dependency of matching type.
  15.  
  16. boolean isConfigurationFrozen()
  17. Return whether this factory's bean definitions are frozen, i.e.
  18.  
  19. void preInstantiateSingletons()
  20. Ensure that all non-lazy-init singletons are instantiated, also considering FactoryBeans.
  21.  
  22. void registerResolvableDependency(Class<?> dependencyType, Object autowiredValue)
  23. Register a special dependency type with corresponding autowired value.
  1. 3.5 继承自BeanDefinitionRegistry接口的方法
    BeanDefinitionRegistrySpring配置文件中每一个<bean>节点元素在Spring容器里都通过一个BeanDefinition对象表示,它描述了Bean的配置信息。而BeanDefinition Registry接口提供了向容器手工注册BeanDefinition对象的方法。
  1. boolean containsBeanDefinition(String beanName)
  2. Check if this registry contains a bean definition with the given name.
  3.  
  4. BeanDefinition getBeanDefinition(String beanName)
  5. Return the BeanDefinition for the given bean name.
  6.  
  7. int getBeanDefinitionCount()
  8. Return the number of beans defined in the registry.
  9.  
  10. String[] getBeanDefinitionNames()
  11. Return the names of all beans defined in this registry.
  12.  
  13. boolean isBeanNameInUse(String beanName)
  14. Determine whether the given bean name is already in use within this registry, i.e.
  15.  
  16. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  17. Register a new bean definition with this registry.
  18.  
  19. void removeBeanDefinition(String beanName)
  20. Remove the BeanDefinition for the given name.
  1. 3.6 序列化支持
  1. private void writeObject(java.io.ObjectOutputStream out)throws IOException
  2. private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException;
  3. private void readObjectNoData()throws ObjectStreamException;
  1. 4 小结:
  1. spring Ioc容器的实现,从根源上是beanfactory,但真正可以作为一个可以独立使用的ioc容器还是DefaultListableBeanFactory,因此可以这么说,
  1. DefaultListableBeanFactory 是整个spring ioc的始祖,研究透它的前生今世对我们理解spring ioc的概念有着重要的作用。
  1. DefaultListableBeanFactory功能的实现是通过实现特定功能的接口来完成。
  1. AbstractAutowireCapableBeanFactory 实现属性的自动绑定功能。
  1. ConfigurableListableBeanFactory提供了对bean定义的分析和修改的便利方法,同时也提供了对单例的预实例化。

ListableBeanFactory提供枚举所有的bean实例,而不是客户端通过名称一个一个的查询得出所有的实例。

  1. BeanDefinitionRegistry 提供了beanDefinition的管理。

Spring之22:DefaultListableBeanFactory的更多相关文章

  1. 【Spring】22、Spring缓存注解@Cache使用

    缓存注解有以下三个: @Cacheable      @CacheEvict     @CachePut @Cacheable(value=”accountCache”),这个注释的意思是,当调用这个 ...

  2. Spring Boot (22) Spring Security

    除了使用拦截器.过滤器实现对没有权限访问的页面跳转到登陆页外,还可以通过框架实现:Spring Security. 使用Spring Security 完成登陆验证: 1.pom.xml添加依赖 &l ...

  3. Spring系列22:Spring AOP 概念与快速入门篇

    本文内容 Spring AOP含义和目标 AOP相关概念 声明式AOP快速入门 编程式创建代理对象 Spring AOP含义和目标 OOP: Object-oriented Programming 面 ...

  4. 一则spring容器启动死锁问题(DefaultListableBeanFactory/DefaultSingletonBeanRegistry)

    线上发现一个问题,应用在启动时会卡死,log上并没有什么异常输出,初判应该是死锁问题. 抓现场的thread dump文件, 确实是有两个线程有deadlock问题. 线程一 "HSFBiz ...

  5. spring源码学习之:spring容器的applicationContext启动过程

    Spring 容器像一台构造精妙的机器,我们通过配置文件向机器传达控制信息,机器就能够按照设定的模式进行工作.如果我们将Spring容器比喻为一辆汽车,可以将 BeanFactory看成汽车的发动机, ...

  6. 【Spring】6、注解大全

    一.@interface Java用  @interface Annotation{ } 定义一个注解 @Annotation,一个注解是一个类. 二.@Override,@Deprecated,@S ...

  7. 【Spring】17、spring cache 与redis缓存整合

    spring cache,基本能够满足一般应用对缓存的需求,但现实总是很复杂,当你的用户量上去或者性能跟不上,总需要进行扩展,这个时候你或许对其提供的内存缓存不满意了,因为其不支持高可用性,也不具备持 ...

  8. 权限管理demo-获取Spring上下文工具

    package com.mmall.common; import org.springframework.beans.BeansException; import org.springframewor ...

  9. IoC之Spring.Net在Mvc项目中的使用

    MVC中使用Spring.net 前面学习了使用Autofac来实现控制反转,这里简单记录Spring.Net实现IoC和DI的步骤 第一步:安装如下Nuget包 (Spring.Web.Mvc) i ...

随机推荐

  1. Docker 常用命令,自用,持续更

    1.进入容器 docker exec -it 容器id /bin/bash docker exec -it db30f533ee1b /bin/bash 2.复制文件到容器 docker cp 文件路 ...

  2. #C++初学记录(算法测试2019/5/5)(深度搜索)

    深度搜索:Oil Deposits GeoSurvComp地质调查公司负责探测地下石油储藏. GeoSurvComp现在在一块矩形区域探测石油,并把这个大区域分成了很多小块.他们通过专业设备,来分析每 ...

  3. 常用的maven仓库地址

    maven 仓库地址: 共有的仓库http://repo1.maven.org/maven2/http://repository.jboss.com/maven2/http://repository. ...

  4. sysfs 控制gpio

    按照下面的命令点亮及熄灭LED pi@raspberrypi:/sys/class/gpio $echo 26 > exportpi@raspberrypi:/sys/class/gpio $ ...

  5. [java.lang.NoSuchMethodError: org.hibernate.Session.createQuery(Ljava/lang/String;)Lorg/hibernate/query/Query;]

    jar包冲突 maven导入的jar包和自己将lib目录的jar同时加入了项目里面了

  6. python gtk 环境

    为Python添加GTK+库:pygtk(windows下安装pygtk) 一.下载需要的文件 昨天晚上就是所需的文件没有找全,我还以为只需要一个pygtk就够了. 1.下载pygtk需要的文件 到p ...

  7. Hive的配置详解和日常维护

    Hive的配置详解和日常维护 一.Hive的参数配置详解 1>.mapred.reduce.tasks  默认为-1.指定Hive作业的reduce task个数,如果保留默认值,则Hive 自 ...

  8. linux: QT安装时出现段错误segmentation fault

    环境:macOS 10.14.6 VMware Fusion版本:11.0.1 QT版本:qt-creator-linux-x86_64-opensource-2.5.2.bin 安装时出现:segm ...

  9. shell编程系列11--文本处理三剑客之sed利用sed删除文本中的内容

    shell编程系列11--文本处理三剑客之sed利用sed删除文本中的内容 删除命令对照表 命令 含义 1d 删除第一行内容 ,10d 删除1行到10行的内容 ,+5d 删除10行到16行的内容 /p ...

  10. Fiddler抓包显示请求时延

    两种方式:配置和加代码.配置只是将隐藏的时延字段显现了出来,格式没法改:加代码就随你写了,格式自己说了算. 先说配置的,在左边框顶部字段名称右击鼠标 -> 点击Customize colums. ...