本文不分析Spring的源码流程,只是介绍一些基础的概念,在阅读源码之前,我们应该首先明确研究的对象是什么,才能有的放矢。

Spring作为BeanFactory, 和现实工厂有着许多类似之处。

需要各种原料Class,存在各个jar包内,jar包内又分为不同的Package。

每一种原料有相应的说明书------BeanDefinition

需要存储说明书的地方 BeanDefinitionRegistry

需要搬运工:BeanFactoryPostProcessor       

需要按照说明书生产零件   newInstance .

各种零件    Singleton

半成品       BeanWrapper

成品    ExposedObject

零件和零件之间有依赖关系  Dependency

需要存储零件的地方

存储半成品的地方

需要存储成品的地方

需要各种工序Processor

需要决定Processor如何执行的地方PostProcessorRegistrationDelegate,

需要有存储工序的地方

需要对零件进行组装    AutowireCapableBeanFactory, 这部分也就是注入依赖的过程。

需要对成品的一些功能进行增强。  对Method进行增强。

Spring BeanFactory和现实工厂的对比_spring

顺着这条线看应该会容易很多。

1: BeanDefinition     一个Class对应一个BeanDefinition,有了BeanDefinition再构建instance。

        可以理解为Class可以分为不同的功能。      

        1.1   普通的bean         

        1.2   能处理@Component的bean  

        1.3   能处理@Configuration的bean   

Spring BeanFactory和现实工厂的对比_ide_02

     

ConfigurationClassBeanDefinition  , 对应@Configuration 修饰的Class类。     ConfigurationClassBeanDefinitionReader 是负责分析ConfigurationClass。

spring 里面有一个非常常见的变量 mbd,   意为getMergedLocalBeanDefinition 。

BeanDefinition 其实是相当复杂的一个类,需要考虑到Bean的各种可能潜在的属性以及整个生命周期。

@Nullable
private volatile Object beanClass;      代表的class
@Nullable
private String scope;                    作用域
private boolean abstractFlag;            是否是abstract类
private boolean lazyInit;                是否是懒加载
private int autowireMode;                autowireMode         
private int dependencyCheck;             是否检查依赖
@Nullable
private String[] dependsOn;               依赖那些其他的beanClass
private boolean autowireCandidate;        候选人
private boolean primary;                  是否是主类
private final Map<String, AutowireCandidateQualifier> qualifiers;        限定    
@Nullable
private Supplier<?> instanceSupplier;      供应商
private boolean nonPublicAccessAllowed;    
private boolean lenientConstructorResolution;    宽容的
@Nullable
private String factoryBeanName;
@Nullable
private String factoryMethodName;
@Nullable
private ConstructorArgumentValues constructorArgumentValues;        构造方法的参数
@Nullable
private MutablePropertyValues propertyValues;    属性
@Nullable
private MethodOverrides methodOverrides;        
@Nullable
private String initMethodName;        init方法
@Nullable
private String destroyMethodName;    销毁方法的名称
private boolean enforceInitMethod;
private boolean enforceDestroyMethod;
private boolean synthetic;        是否是人工合成的
private int role;                   角色
@Nullable
private String description;        描述
@Nullable
private Resource resource;         class文件的位置
@Nullable
private BeanDefinitionHolder decoratedDefinition;
@Nullable
private AnnotatedElement qualifiedElement;
boolean allowCaching = true;
boolean isFactoryMethodUnique = false;
@Nullable
volatile ResolvableType targetType;
@Nullable
volatile Class<?> resolvedTargetType;       //  resolvedTargetType 目标类型目标类型
@Nullable
volatile ResolvableType factoryMethodReturnType;
@Nullable
volatile Method factoryMethodToIntrospect;                 
final Object constructorArgumentLock = new Object();
@Nullable
Executable resolvedConstructorOrFactoryMethod;
boolean constructorArgumentsResolved = false;
@Nullable
Object[] resolvedConstructorArguments;
@Nullable
Object[] preparedConstructorArguments;
final Object postProcessingLock = new Object();
boolean postProcessed = false;
@Nullable
volatile Boolean beforeInstantiationResolved;
@Nullable
private Set<Member> externallyManagedConfigMembers;
@Nullable
private Set<String> externallyManagedInitMethods;
@Nullable
private Set<String> externallyManagedDestroyMethods;

能将事物的本质描述清楚实在是不容易。

 

2:既然有BeanDefinition ,那么就需要有存放BeanDefinition的地方(容器) ,  称为BeanDefinitionRegistry

Spring BeanFactory和现实工厂的对比_spring_03

beanDefinitionMap 就是存放BeanDefinition的地方。  Map<String,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);
}

除此之外还可以给BeanDefinition起一个别名。

3:Singleton   

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

    @Nullable
    Object getSingleton(String var1);

    boolean containsSingleton(String var1);

    String[] getSingletonNames();

    int getSingletonCount();

    Object getSingletonMutex();
}

很明显Singleton全部为Object类型,这意味着在@Autowired 注入依赖时,需要进行类型转换。 注意这里没法进行进行强制类型转换。 这也是spring推荐

使用构造方法注入依赖的原因吧,   类型擦除之后还得再还原原始类型,很复杂。 

Singleton  分为两种: 

        3.1:    不依赖其他Singleton的Singleton

        3.2:    依赖其他Singleton的Singleton

存放Singleton的地方

Spring BeanFactory和现实工厂的对比_ide_04

 

4: ScopedObject

Spring BeanFactory和现实工厂的对比_子类_05

存放 ScopeObject的地方

Spring BeanFactory和现实工厂的对比_jar包_06

 

5:Bean 

        从功能来看:  Bean分为NamedBean DisposableBean  InitializingBean 和 FactoryBean<T>  

6:BeanWrapper

7:存放Singleton和Scope,以及对他们进行加工改造的地方称为BeanFactory  , 实际上Singleton存储在SingletonBeanRegistry ,Scope存在

      RequestContextHolder 中,BeanFactory 提供了桥接入口

    FactoryBean和BeanFactory 的区别,   FactoryBean<T> 带有参数T , FactoryBean 只是生产T对应的BeanDefinition     

    FactoryBean的作用:  有些Bean能够直接通过newInstance 直接构建,有些Bean需要通过反射进行构建,比如@Mapper,@Feign ,@Repository    修饰的

    interface 。这些接口需要通过FactoryBean解析,bangding相应的MethodHandler,  然后注入到BeanDefinition。 注意此时只是注册到BeanDefinition。

8:BeanInstance

9: BeanFactoryPostProcessor       这命名真让人误解

        FactoryBean 不能自己注入到spring中去,需要BeanFactoryPostProcessor才能注入到spring中去。

10: BeanPostProcessor

11:   InstantiationStrategy

12: proxy

13: Interceptor

 

下面介绍一下Processor

 

Spring BeanFactory和现实工厂的对比_构造方法_07

 

了解一两个Processor会对Bean的加工过程有所了解。  个人感觉这种模式和pipeline模式很像。

Processor 没法自行启动,需要委托给 PostProcessorRegistrationDelegate 进行启动。

Processor 的执行有先后顺序关系。 

对于BeanFactoryPostProcessor 而言                registryProcessors  >  regularPostProcessors

对应BeanPostProcessor而言 

priorityOrderedPostProcessors >  orderedPostProcessorNames > nonOrderedPostProcessorNames  > internalPostProcessors

 

和Aop相关的Processor

Spring BeanFactory和现实工厂的对比_ide_08

所有Processor接口的子类,

Spring BeanFactory和现实工厂的对比_ide_09

 

 

BeanFactoryProcessor接口的子类也十分多。

 

Spring BeanFactory和现实工厂的对比_jar包_10

 

 

最后介绍一个超级大Boss    DefaultListableBeanFactory

 

Spring BeanFactory和现实工厂的对比_jar包_11

整个BeanFactory的继承体系也十分庞大。

Spring BeanFactory和现实工厂的对比_spring_12

 

 

spring 最终注入依赖的地方

InjectionMetadata

 

protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs) throws Throwable {
    if (this.isField) {
        Field field = (Field)this.member;
        ReflectionUtils.makeAccessible(field);
        field.set(target, this.getResourceToInject(target, requestingBeanName));
    } else {
        if (this.checkPropertySkipping(pvs)) {
            return;
        }

        try {
            Method method = (Method)this.member;
            ReflectionUtils.makeAccessible(method);
            method.invoke(target, this.getResourceToInject(target, requestingBeanName));
        } catch (InvocationTargetException var5) {
            throw var5.getTargetException();
        }
    }
}

 

程序架构设计应该不只是顺序思维,更应该锻炼立体思维,思前顾后,承上启下,注重接口和继承体系的设计,还应该掌握一些基础基本的专业术语,设计模式。

你应该明确自己研究的对象,怎么描述它,怎么构建它,怎么增强它,怎么存储它,以及怎么使用它。

 

与AOP相关的概念

Advide 。

Spring BeanFactory和现实工厂的对比_spring_13

 

Advisor

Spring BeanFactory和现实工厂的对比_spring_14