一.Spring IOC
IOC容器是一个Map结构,里面包含了控制反转及依赖注入。
- 控制反转:控制反转就是对对象控制权的转移,从程序代码本身反转到了外部容器。把对象的创建、初始化、销毁等工作交给spring容器来做。由spring容器控制对象的生命周期。
- DI依赖注入:DI—Dependency Injection,即“依赖注入”:组件之间依赖关系由容器在运行期决定,形象的说,即由容器动态的将某个依赖关系注入到组件之中。依赖注入的目的并非为软件系统带来更多功能,而是为了提升组件重用的频率,并为系统搭建一个灵活、可扩展的平台。通过依赖注入机制,我们只需要通过简单的配置,而无需任何代码就可指定目标需要的资源,完成自身的业务逻辑,而不需要关心具体的资源来自何处,由谁实现。
二.IOC容器的创建流程
创建Spring容器我们用的最多的是AnnotationConfigApplicationContext及ClassPathXmlApplicationContext等等,通过源码发现他们的根接口都是BeanFactory。
//创建基于注解的springIOC容器
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanConfig.class);
//创建基于配置文件的springIOC容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-beans.xml");
无论是那种创建方式,通过源码发现他们都调用的了他们的父类AbstractApplicationContext#refresh()方法,refresh()方法如下:
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
// 初始化spring上下文
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
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.
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();
contextRefresh.end();
}
}
}
在refresh方法中主要做了如下事情:
- 初始化Spring上下文 prepareRefresh()
主要是设置启动时间,并初始化earlyApplicationListeners及earlyApplicationEvents - 创建BeanFactory obtainFreshBeanFactory()
refreshBeanFactory():如果BeanFactory存在则关闭工程,并重新创建BeanFactory,加载BeanDefinitions - 设置BeanFactory上下文 prepareBeanFactory(beanFactory);
设置BeanFactory属性 - 后置处理BeanFactory
- 调用已注册的BeanFactoryPostProcessors invokeBeanFactoryPostProcessors(beanFactory);
- 注册BeanPostProcessors registerBeanPostProcessors(beanFactory);
- 初始化国际化 initMessageSource();
- 初始化多播器 initApplicationEventMulticaster();
- 注册监听器 registerListeners();
- 非懒加载Bean对象实例化 finishBeanFactoryInitialization(beanFactory);
解决循环依赖及添加动态代理 - 发布相应事件,完成刷新 finishRefresh();