spring初始过程
2018-03-11 20:37
113 查看
spring初始化 可以理解为IOC容器初始化的过程。
IOC: spring核心理念,即控制反转,将设计好的Bean教由框架管理,在需要的时候进行实例化
IOC容器的初始化:
一.代码形式:
实例化org.springframework.context.support.ClassPathXmlApplicationContext注入对应xml文件ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("XXX.xml","XXX.xml");
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}首先,调用父类容器的构造方法(super(parent)方法)为容器设置好Bean资源加载器。然后,再调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations)方法设置Bean定义资源文件的定位路径。最后调用AbstractApplicationContext父类的refresh()方法,该方法基本就是spring初始化核心方法
“ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();”这句以后代码的都是注册容器的信息源和生命周期事件,载入过程就是从这句代码启动。
refresh()方法的作用是:在创建IoC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IoC容器。refresh的作用类似于对IoC容器的重启,在新建立好的容器中对容器进行初始化,对Bean定义资源进行载入
bstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的refreshBeanFactory()方法,启动容器载入Bean定义资源文件的过程,代码如下:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}在该类中只抽象了refreshBeanFactory()方法 具体实现由子类AbstractRefreshableApplicationContext实现方法,代码如下:protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {//如果已经有容器,销毁容器中的bean,关闭容器
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}在这个抽象方法中,先判断BeanFactory是否存在,如果存在则先销毁beans并关闭beanFactory,接着创建DefaultListableBeanFactory,并调用loadBeanDefinitions(beanFactory)装载bean定义同样在该方法中loadBeanDefinitions()也只是抽象方法具体实现是由子类AbstractXmlApplicationContext实现protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//创建XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容器使用该读取器读取Bean定义资源
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的
//祖先父类AbstractApplicationContext继承DefaultResourceLoader,因此,容器本身也是一个资源加载器
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
//为Bean读取器设置SAX xml解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
}
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions. //当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制
initBeanDefinitionReader(beanDefinitionReader); //Bean读取器真正实现加载的方法
loadBeanDefinitions(beanDefinitionReader);
}最后一步调用真正的解析方法
调用其父类AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法读取Bean定义资源。在其抽象父类AbstractBeanDefinitionReader中定义了载入过程(具体解析文件过程略,有时间在分析)
自此spring初始化完成。
IOC: spring核心理念,即控制反转,将设计好的Bean教由框架管理,在需要的时候进行实例化
IOC容器的初始化:
一.代码形式:
实例化org.springframework.context.support.ClassPathXmlApplicationContext注入对应xml文件ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("XXX.xml","XXX.xml");
public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext { @Nullable private Resource[] configResources; public ClassPathXmlApplicationContext() { } public ClassPathXmlApplicationContext(ApplicationContext parent) { super(parent); } public ClassPathXmlApplicationContext(String configLocation) throws BeansException { this(new String[] {configLocation}, true, null); } public ClassPathXmlApplicationContext(String... configLocations) throws BeansException { this(configLocations, true, null); } public ClassPathXmlApplicationContext(String[] configLocations, @Nullable ApplicationContext parent) throws BeansException { this(configLocations, true, parent); } public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh) throws BeansException { this(configLocations, refresh, null); } public ClassPathXmlApplicationContext( String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } } public ClassPathXmlApplicationContext(String path, Class<?> clazz) throws BeansException { this(new String[] {path}, clazz); } public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz) throws BeansException { this(paths, clazz, null); } public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent) throws BeansException { super(parent); Assert.notNull(paths, "Path array must not be null"); Assert.notNull(clazz, "Class argument must not be null"); this.configResources = new Resource[paths.length]; for (int i = 0; i < paths.length; i++) { this.configResources[i] = new ClassPathResource(paths[i], clazz); } refresh(); } @Override @Nullable protected Resource[] getConfigResources() { return this.configResources; } }通过ClassPathXmlApplicationContext构造器将配置文件写入实例,将参数统一后,交由该构造方法统一处理public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}首先,调用父类容器的构造方法(super(parent)方法)为容器设置好Bean资源加载器。然后,再调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations(configLocations)方法设置Bean定义资源文件的定位路径。最后调用AbstractApplicationContext父类的refresh()方法,该方法基本就是spring初始化核心方法
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing.调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识 prepareRefresh(); // Tell the subclass to refresh the internal bean factory.告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从 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.为容器的某些子类指定特殊的BeanPost事件处理器 postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.调用所有注册的BeanFactoryPostProcessor的Bean invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.为BeanFactory注册BeanPost事件处理器.BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件 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初始化方法 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.销毁以创建的单态Bean destroyBeans(); // Reset 'active' flag.取消refresh操作,重置容器的同步标识. 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(); } } }refresh()方法主要为IoC容器Bean的生命周期管理提供条件,Spring IoC容器载入Bean定义资源文件从其子类容器的refreshBeanFactory()方法启动,所以整个refresh()中
“ConfigurableListableBeanFactory beanFactory =obtainFreshBeanFactory();”这句以后代码的都是注册容器的信息源和生命周期事件,载入过程就是从这句代码启动。
refresh()方法的作用是:在创建IoC容器前,如果已经有容器存在,则需要把已有的容器销毁和关闭,以保证在refresh之后使用的是新建立起来的IoC容器。refresh的作用类似于对IoC容器的重启,在新建立好的容器中对容器进行初始化,对Bean定义资源进行载入
bstractApplicationContext的obtainFreshBeanFactory()方法调用子类容器的refreshBeanFactory()方法,启动容器载入Bean定义资源文件的过程,代码如下:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}在该类中只抽象了refreshBeanFactory()方法 具体实现由子类AbstractRefreshableApplicationContext实现方法,代码如下:protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {//如果已经有容器,销毁容器中的bean,关闭容器
destroyBeans();
closeBeanFactory();
}
try {
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
customizeBeanFactory(beanFactory);
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}在这个抽象方法中,先判断BeanFactory是否存在,如果存在则先销毁beans并关闭beanFactory,接着创建DefaultListableBeanFactory,并调用loadBeanDefinitions(beanFactory)装载bean定义同样在该方法中loadBeanDefinitions()也只是抽象方法具体实现是由子类AbstractXmlApplicationContext实现protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//创建XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容器使用该读取器读取Bean定义资源
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的
//祖先父类AbstractApplicationContext继承DefaultResourceLoader,因此,容器本身也是一个资源加载器
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
//为Bean读取器设置SAX xml解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
}
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions. //当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制
initBeanDefinitionReader(beanDefinitionReader); //Bean读取器真正实现加载的方法
loadBeanDefinitions(beanDefinitionReader);
}最后一步调用真正的解析方法
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { //获取Bean定义资源的定位 Resource[] configResources = getConfigResources(); if (configResources != null) { //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位 //的Bean定义资源 reader.loadBeanDefinitions(configResources); } //如果子类中获取的Bean定义资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源 String[] configLocations = getConfigLocations(); if (configLocations != null) { //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位 //的Bean定义资源 reader.loadBeanDefinitions(configLocations); } }Xml Bean读取器(XmlBeanDefinitionReader)
调用其父类AbstractBeanDefinitionReader的 reader.loadBeanDefinitions方法读取Bean定义资源。在其抽象父类AbstractBeanDefinitionReader中定义了载入过程(具体解析文件过程略,有时间在分析)
自此spring初始化完成。
相关文章推荐
- Spring Boot:简化Spring应用初始搭建以及开发过程
- Spring Boot启动过程(六):内嵌Tomcat中StandardHost、StandardContext和StandardWrapper的启动
- Spring启动过程(一)
- Spring启动过程(二)
- Spring 调用ORACLE存储过程的结果集
- MyBatis与Spring整合过程
- spring中IOC容器中的xml加载过程
- Spring配置过程(一)反转控制/依赖注入IOC
- 4. dubbo在spring中的初始代
- spring 启动过程
- spring启动过程之源码跟踪(续beanfactory)--spring Debug
- spring cloud 的学习过程 (一)
- xfire注入spring完整过程(包括注入其他service)
- [Java web]Spring+Struts2+Hibernate整合过程
- spring-core-4.04 源码编译过程记录
- Web环境中Spring的启动过程
- spring-data-redis 使用过程中需要注意的一点(序列化选择)
- spring 定时任务、调用过程
- Spring+MyBatis+JUnit整合测试的搭建过程总结
- Spring Cloud云服务架构 - common-service 项目构建过程