看源码
IoC容器是Spring的核心模块,是抽象了对象管理、依赖关系管理的框架解决方案。Spring 提供了很多的容器,其中 BeanFactory 是顶层容器(根容器),不能被实例化,它定义了所有 IoC 容器必须遵从的一套原则,具体的容器实现可以增加额外的功能,比如我们常用到的ApplicationContext,其下更具体的实现如 ClassPathXmlApplicationContext 包含了解析 xml 等一系列的内容,AnnotationConfigApplicationContext 则是包含了注解解析等一系列的内容。Spring IoC 容器继承体系非常聪明,需要使用哪个层次用哪个层次即可,不必使用功能大而全的。
ApplicationContext是容器的高级接口,BeanFacotry(顶级容器/根容器,规范了/定义了容器的基础行为) Spring应用上下文,官方称之为 IoC容器(错误的认识:容器就是map而已;准确来说,map是ioc容器的一个成员, 叫做单例池,singletonObjects。容器是一组组件和过程的集合,包括BeanFactory、单例池、BeanPostProcessor等以及之间的协作流程)
package com.lagou.edu;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class LagouBean implements InitializingBean, ApplicationContextAware {
/*private ItBean itBean;
public void setItBean(ItBean itBean) {
this.itBean = itBean;
}*/
private int num;
public void setNum(int num) {
this.num = num;
}
/**
* 构造函数
*/
public LagouBean(){
System.out.println("LagouBean 构造器...");
}
/**
* InitializingBean 接口实现
*/
public void afterPropertiesSet() throws Exception {
System.out.println("LagouBean InitializingBean#afterPropertiesSet...");
}
public void print() {
System.out.println("print方法业务逻辑执行");
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
System.out.println("setApplicationContext....");
}
/**
* BeanFactoryPostProcessor的实现类构造函数...
* BeanFactoryPostProcessor的实现方法调用中......
* BeanPostProcessor 实现类构造函数...
* LagouBean 构造器...
* setApplicationContext....
* BeanPostProcessor 实现类 postProcessBeforeInitialization 方法被调用中......
* LagouBean afterPropertiesSet...
* BeanPostProcessor 实现类 postProcessAfterInitialization 方法被调用中......
* com.lagou.edu.LagouBean@6ad3381f
*/
}
package com.lagou.edu;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
public class MyBeanPostProcessor implements BeanPostProcessor {
public MyBeanPostProcessor() {
System.out.println("BeanPostProcessor 实现类构造函数...");
}
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if("lagouBean".equals(beanName)) {
System.out.println("BeanPostProcessor 实现类 postProcessBeforeInitialization 方法被调用中......");
}
return bean;
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if("lagouBean".equals(beanName)) {
System.out.println("BeanPostProcessor 实现类 postProcessAfterInitialization 方法被调用中......");
}
return bean;
}
}
BeanFactoryPostProcessor接口实现类
package com.lagou.edu;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public MyBeanFactoryPostProcessor() {
System.out.println("BeanFactoryPostProcessor的实现类构造函数...");
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
System.out.println("BeanFactoryPostProcessor的实现方法调用中......");
}
}
import com.lagou.edu.LagouBean;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class IocTest {
/**
* Ioc 容器源码分析基础案例
*/
@Test
public void testIoC() {
// ApplicationContext是容器的高级接口,BeanFacotry(顶级容器/根容器,规范了/定义了容器的基础行为)
// Spring应用上下文,官方称之为 IoC容器(错误的认识:容器就是map而已;准确来说,map是ioc容器的一个成员,
// 叫做单例池, singletonObjects,容器是一组组件和过程的集合,包括BeanFactory、单例池、BeanPostProcessor等以及之间的协作流程)
/**
* Ioc容器创建管理Bean对象的,Spring Bean是有生命周期的,在特殊方法打断点可知
* bean构造函数执行、初始化方法执行 、Bean后置处理器的before/after方法:AbstractApplicationContext#refresh()#finishBeanFactoryInitialization()
*
* Bean工厂后置处理器构造函数执行、Bean工厂后置处理器方法执行:AbstractApplicationContext#refresh()#invokeBeanFactoryPostProcessors()
*
* Bean后置处理器构造函数执行:AbstractApplicationContext#refresh()#registerBeanPostProcessors()
*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
LagouBean lagouBean = applicationContext.getBean(LagouBean.class);
System.out.println(lagouBean);
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
/**
* 第⼀步:刷新前的预处理
* 表示在真正刷新之前需要准备做的事情:
* 设置sping容器的启动时间
* 开启活跃状态,撤销关闭状态
* 验证环境信息里一些必要的属性
*/
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
/**
* 第⼆步:获取BeanFactory,有了bean工厂才能创建bean,默认实现是DefaultListableBeanFactory
* 读取配置文件信息,将 中的信息封装成BeanDefition 并注册到 BeanDefitionRegistry(是一个map)
*/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
// 第三步:BeanFactory的预准备⼯作(BeanFactory进⾏⼀些设置,⽐如context的类加载器等
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
// 第四步:BeanFactory准备⼯作完成后进⾏的后置处理⼯作
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 第五步: 实例化并调用实现了BeanFactoryPostProcessor接口的Bean
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 第六步:注册BeanPostProcessors(Bean的后置处理器)
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 第七步:初始化MessageSource组件(做国际化功能;消息绑定,消息解析);
initMessageSource();
// Initialize event multicaster for this context.
// 第八步:初始化事件分发器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 第九步:⼦类重写这个⽅法,在容器刷新的时候可以⾃定义逻辑
onRefresh();
// Check for listener beans and register them.
// 第⼗步:注册应⽤的监听器。就是注册实现了ApplicationListener接⼝的监听器
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
/**
* 第十一步:
* 初始化所有剩下的非懒加载的单例bean
* 初始化创建非懒加载方式的单例bean实例(未设置属性)
* 填充属性
* 初始化方法调用,(比如调用afterPropertiesSet方法、init-method方法)
* 调用BeanPostProcessor(bean后置处理器)对实例bean进行后处置
*/
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
// 第⼗⼆步:完成context的刷新。主要是调⽤LifecycleProcessor的onRefresh()⽅法,并且发布事 (ContextRefreshedEvent)
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();
}
}
}