从把spring下下来,导入到eclipse,花了几个小时的时间。

本来壮志雄心的说要,满满深入学习研读spring源码,现在看来还是不太现实,太难懂了,各种依赖,说明都是英文,整个串起来理解,深入研读太难了。

想想还是自己学得不够深入,现在研读还为时尚早吧。还是等一段时间再研读。现在我还是小菜鸟,深读太困难了。。。

下面贴出对spring beans的学习:

1. DefaultListableBeanFactory作用说明:
默认实现了ListableBeanFactory和BeanDefinitionRegistry: 一个基于bean定义对象的成熟的bean工厂 。
典型的用法是,在访问bean之前,首先要注册所有的bean定义(通常从一个bean定义文件读入)。Bean定义的查找由此变得很方便,由本地化的一个bean定义表来操作预先定义好的bean定义元数据对象。
可以被用作一个单独的bean工厂,或者普通bean工厂的一个超类。注意:特定格式bean definition的解析器可以自己实现,也可以使用原有的解析器,如:PropertiesBeanDefinitionReader和XmLBeanDefinitionReader。
作为一个可选的对于ListableBeanFactory接口的实现,可以看看这个StaticListableBeanFactory 类,它控制通过已经存在的bean实例而不是由bean定义创建一个新的bean实例。
 
2. DefaultListableBeanFactory的继承关系:
3.好了,可以进入DefaultListableBeanFactory的大千世界了:
直接继承关系:
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
            implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
 }
 

 
3.1 静态方法:
static {
            try {
                 javaUtilOptionalClass =
                          ClassUtils. forName("java.util.Optional", DefaultListableBeanFactory.class .getClassLoader());
           }
            catch (ClassNotFoundException ex) {
                 // Java 8 not available - Optional references simply not supported then.
           }
            try {
                 javaxInjectProviderClass =
                          ClassUtils. forName("javax.inject.Provider", DefaultListableBeanFactory.class .getClassLoader());
           }
            catch (ClassNotFoundException ex) {
                 // JSR-330 API not available - Provider interface simply not supported then.
           }
     }

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

Commons Lang
The standard Java libraries fail to provide enough methods for manipulation of its core classes. Apache Commons Lang provides these extra methods. 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
ClassUtils.forName方法是class.forname的重写,返回一个类的实例,区别请参考源码。
 
上述静态方法中返回了javax.inject.Provider的一个实例,那么我们揭开javax.inject.Provider的面纱看看它到底起了什么作用。
语法:public interface Provider<T>

提供了一个 T的实例. 通常作为一个依赖注入容器器的父接口. 可以注入任何类型的 T, 当然也可以注入 Provider<T>. 相对于直接注入 T,注入 Provider<T>有如下作用:

  • 检索多个实例.
  • 延迟或者选择性的检索一个实例.
  • 打破循环依赖.
  • 抽象的scope,可以从一个包含scope的更小的scope中检索一个实例。

实例代码:

   class Car {
@Inject Car(Provider<Seat> seatProvider) {
Seat driver = seatProvider.get();
Seat passenger = seatProvider.get();
...
}
}
 
 

 

3.2 继承自AbstractAutowireCapableBeanFactory的方法:

AbstractAutowireCapableBeanFactory的作用:

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

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

 
这个方法用来实现类型的自动绑定.
 
在DefaultListableBeanFactory中实现了AbstractAutowireCapableBeanFactory.copyConfigurationFrom:
@Override
     public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
            super.copyConfigurationFrom( otherFactory);
            if ( otherFactory instanceof DefaultListableBeanFactory) {
                DefaultListableBeanFactory otherListableFactory = (DefaultListableBeanFactory) otherFactory ;
                 this. allowBeanDefinitionOverriding = otherListableFactory .allowBeanDefinitionOverriding ;
                 this. allowEagerClassLoading = otherListableFactory .allowEagerClassLoading ;
                 this. autowireCandidateResolver = otherListableFactory .autowireCandidateResolver ;
                 this. resolvableDependencies.putAll( otherListableFactory.resolvableDependencies );
           }
     }
 
其中:
allowBeanDefinitionOverriding定义了是否允许同名的不同bean definition再次进行注册;
allowEagerClassLoading 定义了是否允许eager类(相对于lazy)的加载,甚至延迟初始化的bean的加载。
autowireCandidateResolver是一个策略接口,用来决定一个特定的bean definition 是否满足做一个特定依赖的自动绑定的候选项,方法如下所示:
 
protected boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor, AutowireCandidateResolver resolver)
                 throws NoSuchBeanDefinitionException {
 
           String beanDefinitionName = BeanFactoryUtils.transformedBeanName( beanName);
            if (containsBeanDefinition( beanDefinitionName)) {
                 return isAutowireCandidate(beanName, getMergedLocalBeanDefinition(beanDefinitionName ), descriptor , resolver);
           }
            else if (containsSingleton( beanName)) {
                 return isAutowireCandidate(beanName, new RootBeanDefinition(getType(beanName )), descriptor , resolver );
           }
            else if (getParentBeanFactory() instanceof DefaultListableBeanFactory) {
                 // No bean definition found in this factory -> delegate to parent.
                 return ((DefaultListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName , descriptor, resolver);
           }
            else if (getParentBeanFactory() instanceof ConfigurableListableBeanFactory) {
                 // If no DefaultListableBeanFactory, can't pass the resolver along.
                 return ((ConfigurableListableBeanFactory) getParentBeanFactory()).isAutowireCandidate(beanName , descriptor);
           }
            else {
                 return true;
           }
     }
 
protected boolean isAutowireCandidate(String beanName, RootBeanDefinition mbd,
                DependencyDescriptor descriptor, AutowireCandidateResolver resolver) {
 
           String beanDefinitionName = BeanFactoryUtils.transformedBeanName( beanName);
           resolveBeanClass( mbd, beanDefinitionName);
            if ( mbd. isFactoryMethodUnique) {
                 boolean resolve;
                 synchronized ( mbd. constructorArgumentLock) {
                      resolve = (mbd. resolvedConstructorOrFactoryMethod == null );
                }
                 if ( resolve) {
                      new ConstructorResolver(this).resolveFactoryMethodIfPossible(mbd );
                }
           }
            return resolver.isAutowireCandidate(
                      new BeanDefinitionHolder( mbd, beanName, getAliases(beanDefinitionName)), descriptor );
     }
 

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

AbstractAutowireCapableBeanFactory的copyConfigurationFrom方法:

    @Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
super.copyConfigurationFrom(otherFactory);
if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
AbstractAutowireCapableBeanFactory otherAutowireFactory =
(AbstractAutowireCapableBeanFactory) otherFactory;
this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
}
}

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

private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();

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

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

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

父类AbstractBeanFactory的copyConfigurationFrom的实现如下:

    @Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
Assert.notNull(otherFactory, "BeanFactory must not be null");
setBeanClassLoader(otherFactory.getBeanClassLoader());
setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
if (otherFactory instanceof AbstractBeanFactory) {
AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
this.customEditors.putAll(otherAbstractFactory.customEditors);
this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
this.scopes.putAll(otherAbstractFactory.scopes);
this.securityContextProvider = otherAbstractFactory.securityContextProvider;
}
else {
setTypeConverter(otherFactory.getTypeConverter());
}
}

其中

customEditors 是自定义的属性编辑器,适用于该beanFactory的所有bean。
propertyEditorRegistrars属性编辑器的注册器,使用于该beanFactory的所有bean。
beanPostProcessors 创建bean时应用的beanPostProcessors。
hasInstantiationAwareBeanPostProcessors 表明是否注册有任何的InstantiationAwareBeanPostProcessors。
hasDestructionAwareBeanPostProcessors表明是否注册有任何的DestructionAwareBeanPostProcessors
scopes:域标识符和对应域的键值对集合。

securityContextProvider 运行SecurityManager时使用的security context

 
3.3 继承自ListableBeanFactory接口的方法
ListableBeanFactory是beanFactory接口的扩展接口,它可以枚举所有的bean实例,而不是客户端通过名称一个一个的查询得出所有的实例。要预加载所有的bean定义的beanfactory可以实现这个接口来。该 接口定义了访问容器中Bean基本信息的若干方法,如查看Bean的个数、获取某一类型Bean的配置名、查看容器中是否包括某一Bean等方法;
containsBeanDefinition(String beanName)
Check if this bean factory contains a bean definition with the given name. findAnnotationOnBean(String beanName, Class<A> annotationType)
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. getBeanDefinitionCount()
Return the number of beans defined in the factory. getBeanDefinitionNames()
Return the names of all beans defined in this factory. getBeanNamesForType(Class<?> type)
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. getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit)
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. getBeansOfType(Class<T> type)
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. getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit)
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. getBeansWithAnnotation(Class<? extends Annotation> annotationType)
Find all beans whose Class has the supplied Annotation type.
3.4 继承自ConfigurableListableBeanFactory接口的方法
ConfigurableListableBeanFactory 它同时继承了ListableBeanFactory,AutowireCapableBeanFactory和ConfigurableBeanFactory,提供了对bean定义的分析和修改的便利方法,同时也提供了对单例的预实例化。
void freezeConfiguration()
Freeze all bean definitions, signalling that the registered bean definitions will not be modified or post-processed any further. BeanDefinition getBeanDefinition(String beanName)
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). void ignoreDependencyInterface(Class<?> ifc)
Ignore the given dependency interface for autowiring. void ignoreDependencyType(Class<?> type)
Ignore the given dependency type for autowiring: for example, String. boolean isAutowireCandidate(String beanName, DependencyDescriptor descriptor)
Determine whether the specified bean qualifies as an autowire candidate, to be injected into other beans which declare a dependency of matching type. boolean isConfigurationFrozen()
Return whether this factory's bean definitions are frozen, i.e. void preInstantiateSingletons()
Ensure that all non-lazy-init singletons are instantiated, also considering FactoryBeans. void registerResolvableDependency(Class<?> dependencyType, Object autowiredValue)
Register a special dependency type with corresponding autowired value.
3.5 继承自BeanDefinitionRegistry接口的方法
BeanDefinitionRegistry:Spring配置文件中每一个<bean>节点元素在Spring容器里都通过一个BeanDefinition对象表示,它描述了Bean的配置信息。而BeanDefinition Registry接口提供了向容器手工注册BeanDefinition对象的方法。
boolean containsBeanDefinition(String beanName)
Check if this registry contains a bean definition with the given name. BeanDefinition getBeanDefinition(String beanName)
Return the BeanDefinition for the given bean name. int getBeanDefinitionCount()
Return the number of beans defined in the registry. String[] getBeanDefinitionNames()
Return the names of all beans defined in this registry. boolean isBeanNameInUse(String beanName)
Determine whether the given bean name is already in use within this registry, i.e. void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
Register a new bean definition with this registry. void removeBeanDefinition(String beanName)
Remove the BeanDefinition for the given name.
3.6 序列化支持
 private void writeObject(java.io.ObjectOutputStream out)throws IOException
private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException;
private void readObjectNoData()throws ObjectStreamException;
4 小结:
spring Ioc容器的实现,从根源上是beanfactory,但真正可以作为一个可以独立使用的ioc容器还是DefaultListableBeanFactory,因此可以这么说,
DefaultListableBeanFactory 是整个spring ioc的始祖,研究透它的前生今世对我们理解spring ioc的概念有着重要的作用。
DefaultListableBeanFactory功能的实现是通过实现特定功能的接口来完成。
AbstractAutowireCapableBeanFactory 实现属性的自动绑定功能。
ConfigurableListableBeanFactory提供了对bean定义的分析和修改的便利方法,同时也提供了对单例的预实例化。

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

BeanDefinitionRegistry 提供了beanDefinition的管理。

spring beans 源码解读的更多相关文章

  1. spring beans源码解读之 ioc容器之始祖--DefaultListableBeanFactory

    spring Ioc容器的实现,从根源上是beanfactory,但真正可以作为一个可以独立使用的ioc容器还是DefaultListableBeanFactory,因此可以这么说, DefaultL ...

  2. spring beans源码解读

    spring beans下面有如下源文件包: org.springframework.beans, 包含了操作java bean的接口和类.org.springframework.beans.anno ...

  3. spring beans源码解读之--总结篇

    spring beans下面有如下源文件包: org.springframework.beans, 包含了操作java bean的接口和类.org.springframework.beans.anno ...

  4. spring beans源码解读之--Bean的注解(annotation)

    随着spring注解的引入,越来越多的开发者开始使用注解,这篇文章将对注解的机制进行串联式的讲解,不求深入透彻,但求串起spring beans注解的珍珠,展示给大家. 1. spring beans ...

  5. spring beans源码解读之--bean definiton解析器

    spring提供了有两种方式的bean definition解析器:PropertiesBeanDefinitionReader和XmLBeanDefinitionReader即属性文件格式的bean ...

  6. spring beans源码解读之--Bean的定义及包装

    bean的定义,包装是java bean的基础.再怎么强调它的重要性都不为过,因此深入 了解这块的代码对以后的代码研究可以起到事半功倍的功效. 1. Bean的定义BeanDefinition 1.1 ...

  7. spring beans源码解读之--XmlBeanFactory

    导读: XmlBeanFactory继承自DefaultListableBeanFactory,扩展了从xml文档中读取bean definition的能力.从本质上讲,XmlBeanFactory等 ...

  8. spring beans源码解读之--BeanFactory的注册

    beanFactory的继承关系如下图所示: (图片来源:http://www.myexception.cn/software-architecture-design/925888.html) 在上节 ...

  9. spring beans源码解读之--BeanFactory进化史

    BeanFactory是访问bean容器的根接口,它是一个bean容器的基本客户端视图. 先让我们看看beanfactory的前生后世吧! beanFactory有四个重要的子接口: SimpleJn ...

随机推荐

  1. pyspider—爬取下载图片

    以第一ppt网站为例:http://www.1ppt.com/ from pyspider.libs.base_handler import * import urllib2,HTMLParser,r ...

  2. no crontab for root 解决方案

    root用户下 输入 crontab -l 显示 no crontab for root  例如: [root@localhost ~]# crontab -l no crontab for root ...

  3. python爬虫之下载京东页面图片

    import requests from bs4 import BeautifulSoup import time import re t = 0 #用于给图片命名 for i in range(10 ...

  4. Lograge(2350✨) 在产品环境显示定制改良的日志输出。

    Lograge https://github.com/roidrage/lograge 改良Rails默认的请求日志的记录. 它会精明的处理好那些noisy和无用的,未解析的,在context中运行多 ...

  5. Linux命令详解-touch

    linux的touch命令不常用,一般在使用make的时候可能会用到,用来修改文件时间戳,或者新建一个不存在的文件. 1.命令格式: touch [选项]... 文件... 2.命令参数: -a 或- ...

  6. 我的 VSCode 常用扩展

    Beautify (option+shift+F) Bookmarks (option+option+k,l,j) Debugger for Chrome Docker EditorConfig fo ...

  7. VS2013 VC++的.cpp文件调用CUDA的.cu文件中的函数

    CUDA 8.0在函数的调用中方便的让人感动.以下是从网上学到的VC++的.cpp文件调用CUDA的.cu文件中的函数方法,和一般的VC++函数调用的方法基本没差别. 使用的CUDA版本为CUDA 8 ...

  8. SPOJ-394-ACODE - Alphacode / dp

    ACODE - Alphacode #dynamic-programming Alice and Bob need to send secret messages to each other and ...

  9. VMware虚拟机创建安装之后不出现VMnet1和VMnet8虚拟网卡

    大家可能遇到过安装虚拟机之后,不出现这两张虚拟网卡,造成一系列的网络问题 VMware虚拟机无法将网络改为桥接状态 本人亲试可行的解决办法 首先把你之前安装的VMware虚拟机卸载,清理得一干二净: ...

  10. 进程上下文频繁切换导致load average过高

    一.问题现象 现网有两台虚拟机主机95%的cpu处于idle状态,内存使用率也不是特别高,而主机的load average达到了40多. 二.问题分析 先在主机上通过top.free.ps.iosta ...