Spring IOC 中涉及的重要接口

  • BeanDefinition
    Bean的描述信息,实现类包括 RootBeanDefinitionGenericBeanDefinition,Bean的描述信息中定义了一系列Bean的信息,比如:beanClassNamescopelazyinitdependsOnprimaryinitMethodNamedestroyMethodNameisSingtonisAbstract等信息。

  • BeanDefinitionReader

    用于解析Bean的资源阅读器,比如针对于XML文件的配置的Bean,实现类XmlBeanDefinitionReader,针对properties文件的配置的Bean,实现类为PropertiesBeanDefinitionReaderSpring在启动时会将xml文件通过loadBeanDefinitions方法进行解析。

  • BeanFactory
    IOC容器实现的顶层接口,默认的实现为DefaultListableBeanFactorySpring Bean 的整个生命周期都是由DefaultListableBeanFactory去管理的,这个类非常的重要

  • BeanFactoryPostProcessor

    这个接口是BeanFactory的增强处理器,用于在Bean加载为BeanDefinition之后的扩展,比如实现类PlaceHolderConfigurerSupport 就是用来处理占位符解析的,当我在xml文件中配置jdbc信息的时候,通过是用${xxx.jdbUrl}这种方式配置数据库连接的时候,就是通过这个类来处理和解析的。

  • Aware

    这个接口,他下面有一堆的子接口,比如BeanNameAwareApplicationContextAwareBeanFactoryAwareEnvironmentAware等,可以通过实现这些接口完成ioc容器中特定信息的设置,比如EnvironmentAware,可以在Bean创建过程中设置环境信息到对应的Bean对象中,后期通过bean对象获取环境信息数据。

  • BeanPostProcessor

    这个接口是Bean的增强处理器,用于在Bean进行初始化时调用init-method方法的前后进行增强,他有两个方法:postProcessBeforeInitializationpostProcessAfterInitialization,分别用于bean初始化方法init-method之前和之后调用,当然还可以进行很多扩展,比如aop就是通过postProcessAfterInitialization方法中去创建动态代理对象。

Spring Bean 的生命周期

img

  1. 首先通过BeanDefinitionReader将xml中的Bean配置加载到BeanDefinition

  2. 然后将BeanDefinition放入DefaultListableBeanFacotrybeanDefinitionMapbeanDefinitionNames集合中

  3. 然后调用BeanFactoryPostProcessor@postProcessorBeanFactory对容器中的BeanDefinition的属性进行增强解析

  4. 然后通过反射调用对象的构造函数进行对象的实例化

  5. 然后调用populateBean进行属性填充

  6. 然后调用初始化方法initializeBean,初始化时又会先调用invokeAwareMethods方法执行一堆的Aware方法

  7. 然后BeanPostProcessor@postProcessBeforeInitialization方法执行bean增强器的前置处理

  8. 然后调用InitializingBean@afterPropertiesSet方法或者是调用自定义的init-method方法

  9. 然后调用BeanPostProcessor@postProcessAfterInitialization方法执行bean增强的后置处理

  10. 最后完成Bean的创建,最终放入一级缓存singletonObjects

Spring创建bean

在我们使用Spring时一般通过下的方法:

1
2
3
4
5
6
7
8
9
@ComponentScan("com.lq.spring")
public class Context {

public static void main(String[] args) {
ApplicationContext ac = new AnnotationConfigApplicationContext(Context.class);
UserService bean = ac.getBean(UserService.class);
System.out.println(bean.getUsername());
}
}

上面代码中的AnnotationConfigApplicationContextApplicationContext的一个实现类。这个类是用来解析注解的,其他的还有解析xml的,解析classpath的,但这些类中最核心的方法refresh来自它们一个父类的AbstractApplicationContext。下面是这类的构造方法:

1
2
3
4
5
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
this();
register(componentClasses); //扫描需要把哪些类加载到Springr容器
refresh();
}

refresh方法

AbstractApplicationContext#refresh,这个方法中总共有15个方法,Spring源码的精髓就是这15个方法中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备工作,加载环境变量等操作
// 1、设置容器启动时间
// 2、设置停止状态为false
// 3、设置活跃状态为true
// 4、获取Environment对象,并设置属性值
// 5、设置监听器和事件的集合,模式为空的集合
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
// 告诉子类刷新内部bean工厂,获取刷新的bean工厂 默认为DefaultListableBeanFactory 并且加载BeanDefinition
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
// 准备BeanFactory 设置一些属性
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
// 允许子类进行扩展BeanFactoryPostProcessor 自定义的BeanFactoryPostProcessor
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
// 实例化并执行BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
// 实例化并注册BeanPostProcessor
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
// 国际化设置
initMessageSource();

// Initialize event multicaster for this context.
// 实例化事件多播器
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
// 初始化特定上下文子类中的其他特殊bean,web容器
onRefresh();

// Check for listener beans and register them.
// 检查listener bean 并注册它们 注册监听器
registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.
// 实例化所有剩余的(非惰性初始化)单例。
finishBeanFactoryInitialization(beanFactory);

// Last step: publish corresponding event.
// 发布相应的事件
finishRefresh();
}

catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}

// Destroy already created singletons to avoid dangling resources.
// 销毁Bean
destroyBeans();

// Reset 'active' flag.
cancelRefresh(ex);

// Propagate exception to caller.
throw ex;
}

finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}