Spring框架中IoC初始化流程
1. 以ClassPathXmlApplicationContext这个ApplicationContext实现类来讲,我们在这一段代码中分析IoC容器的初始化流程
//1.获取核心容器对象 ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
2. ClassPathXmlApplicationContext在它的构造器方法中,完成了配置文件的定位并调用refresh方法
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { super(parent); this.setConfigLocations(configLocations);//定位配置文件 if (refresh) { this.refresh(); } }
3. 重点就是refresh()方法,它是IoC容器初始化的核心,BeanFactory对象的创建,ApplicationContext中高级功能的配置都是在这一步完成
public void refresh() throws BeansException, IllegalStateException { synchronized(this.startupShutdownMonitor) { this.prepareRefresh(); //1.获取BeanFactory对象,完成BeanDefinition的加载,默认实现是DefaultListableBeanFactory ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory(); //2.完成BeanFactory的一些设置 this.prepareBeanFactory(beanFactory); try { this.postProcessBeanFactory(beanFactory);//在ClassPathXmlApplicationContext实现中这里是一个空方法 //3.在Spring容器中找出实现了BeanFactoryPostProcessor接口的processor并执行 this.invokeBeanFactoryPostProcessors(beanFactory); //4.从Spring容器中找出的BeanPostProcessor接口的bean,并设置到BeanFactory的属性中。之后bean被实例化的时候会调用这个BeanPostProcessor。 this.registerBeanPostProcessors(beanFactory); //5.加载一系列的组件 this.initMessageSource(); this.initApplicationEventMulticaster(); this.onRefresh(); this.registerListeners(); //6.实例化BeanFactory中已经被注册但是未实例化的所有实例(懒加载的不需要实例化) this.finishBeanFactoryInitialization(beanFactory); this.finishRefresh(); } catch (BeansException var9) { if (this.logger.isWarnEnabled()) { this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9); } this.destroyBeans(); this.cancelRefresh(var9); throw var9; } finally { this.resetCommonCaches(); } } }
在这里介绍一下BeanFactoryPostProcessor接口和BeanPostProcessor接口,它们是Spring开放给开发者的两个扩展接口
BeanFactoryPostProcessor的作用是在Bean实例化前修改Bean的定义(我们可以在这一步对Bean的属性和作用域进行修改),BeanPostProcessor接口里有两个方法,分别在Bean初始化前后执行,我们可以通过重写这两个方法对Bean做一些处理,比如Spring的AOP的实现就依赖于这个接口。

浙公网安备 33010602011771号