Spring初始化
在Java开发Web应用时,有个web.xml文件,可以说这是我们开发代码的入口。web容器就是通过这个配置文件载入我们的程序。
在使用Spring时,我们都会在web.xml配置一个listener来启动Spring。
<listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
ContextLoaderListener
ContextLoaderListener实现了ServletContextListener接口。所以载入ContextLoaderListener时,会调用contextInitialized()进行初始化操作,关闭web应用时,调用contextDestroyed()。
contextInitialized()只做了一件事,就是调用initWebApplicationContext(event.getServletContext())。
initWebApplicationContext是ContextLoader的方法,ContextLoaderListener继承了ContextLoader从而获得了ContextLoader的功能。
ContextLoader
ContextLoader是实际执行应用程序上下文初始化的地方。
initWebApplicationContext方法
初始化方法的第一个任务是创建一个WebApplicationContext。
if (this.context == null) { this.context = createWebApplicationContext(servletContext); }
WebApplicationContext
web应用程序的上下文。一个提供配置web应用程序的接口。继承了ApplicationContext。在web应用中,我们离不开request,和response,这两个东西都在ServletContext中,webapplication的getServletContext()方法返回了ServletContext,从而得到httpservletrequest和httpservletresponse。
回到createWebApplicationContext,这里实际上是读取ContextLoader.properties配置文件(在spring-web包中),得到org.springframework.web.context.support.XmlWebApplicationContext字符串,
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
然后利用反射实例化一个XmlWebApplicationContext。
ReflectionUtils.makeAccessible(ctor); return ctor.newInstance(args);
XmlWebApplicationContext被转型为ConfigurableWebApplicationContext。
接着调用configureAndRefreshWebApplicationContext()方法,这里会把转型来的ConfigurableWebApplicationContext和ServletContext传入到该方法中,然后把ServletContext设置到ConfigurableWebApplicationContext中
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; configureAndRefreshWebApplicationContext(cwac, servletContext);
然后调用ConfigurableWebApplicationContext的refresh()方法。
wac.refresh();
refresh()是重头戏,这里面完成了Spring容器的具体的初始化过程。
这个过程包括配置得见的读取、解析、注册到beanFactory等。
refresh的具体实现在AbstractApplicationContext类中。
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. 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); // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // 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(); } } }
- prepareRefresh()
刷新上下文的前期准备工作。设置启动日期和活跃标志等。
- obtainFreshBeanFactory()
获得刷新后的BeanFactory,即刷新Spring容器。这里创建的beanFactory是DefaultListableBeanFactory。
DefaultListableBeanFactory beanFactory = createBeanFactory()
创建完后,调用
loadBeanDefinitions(beanFactory)
BeanDefinition是配置文件中</bean>在Spring内部的表现形式,是bean的数据结构。加载BeanDefinition的任务实际上是由XmlBeanDefinitionReader完成的,所以loadBeanDefinitions()方法内部创建了一个XmlBeanDefinitionReader实例,bean被注册加入到BeanFactory中的Map中。bean的注册又需要BeanDefinitionRegistry。
loadBeanDefinitions(beanFactory)实际上是初始化XmlBeanDefinitionReader的过程,为加载BeanDefinition做准备。真正的加载BeanDefinition是
loadBeanDefinitions(beanDefinitionReader);
加载过程:
根据配置文件得到Resource和InputSource,然后生成Document对象,
创建BeanDefinitionDocumentReader,调用documentReader.registerBeanDefinitions(doc, createReaderContext(resource))。
创建BeanDefinitionParserDelegate,他会解析Document。Document中的每个Bean都会解析成一个BeanDefinitionHolder。
BeanDefinitionHolder中持有了BeanDefinition对象,definitionHolder可以通过getBeanDefinition()得到BeanDefinition。
bean会被注册到DefaultListableBeanFactory的一个Map中,注册通过BeanDefinitionRegistry的registerBeanDefinition方法完成。
相关推荐
beanFactory.preInstantiateSingletons()的初始化过程详解,包含了所有的调用过程。
Spring Bean创建初始化流程
本篇文章主要介绍了Spring 中如何控制2个bean中的初始化顺序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
spring的初始化,可以让初学者了解soring的开发过程,让开发轻松进入开发大门。
干净的spring初始化工程,包含ioc,di,datasource,但是不包含aop
主要介绍了Spring初始化和销毁的实现方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
SpringBoot项目启动时实现调用一次初始化方法
3、通过spring的xml bean配置或bean注解指定初始化方法,如下面实例的initMethod方法通过@bean注解指定。 销毁的时候实现的方法 1、通过java提供的@PreDestroy注释; 2、通过实现spring提供的DisposableBean接口,并...
Spring的IoC容器初始化源码解析,包括资源定位、加载、注册3个过程
主要给大家介绍了Spring中如何初始化泛型类,文中给出详细的介绍和方法实例,对大家的理解和学习具有一定的参考借鉴价值,有需要的朋友可以参考学习,下面来一起看看吧。
spring配置对象实例化后执行的方法,两种实现比对,通过InitializingBean接口,并实现arterPropertiesSet()方法;或者通过applicationContext.xml配置init-method属性
初始化后可访问Spring管理的Bean
Spring 源码分析(Bean的初始化) 前言 本篇文章是个人第一次看spring源码并总结,同时也参考了下面这篇博客。基本也是按照他的思路来理解的。这也算是第一版个人简易理解。也算是窥见spring的冰山一角,之后也会...
主要介绍了Spring Bean的初始化和销毁,结合实例形式详细分析了Spring Bean的初始化和销毁相关配置、使用方法及操作注意事项,需要的朋友可以参考下
搭建一个Web服务,实现一个服务端,怎么样来实现一个客户端,并相互传递数据。就算调用别人的服务时,也能知道大概是怎么样实现的。
下面小编就为大家带来一篇浅谈spring容器中bean的初始化。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
Spring 延迟实例化
附件是在Spring Boot项目中使用CommandLineRunner接口来执行一些资源初始化的演示,该文档也详细的介绍了在@Component注解的类中可以注入@Controller,并把获取的数据存放到其他Bean类中的私有静态变量,算是对自己...
IOC容器的初始化分为三个过程实现:第一个过程是Resource资源定位。这个Resouce指的是BeanDefinition的资源定位。这个过程就是容器找数据的过程,就像水桶装水需要先找到水一样。 第二个过程是BeanDefinition的载入...
1.首先使用spring初始化器新建一个工程: 2.取好自己的工程名,并且选择==打包方式为war==的形式: 3.工程自动创建的两个类 4.创建webapp、WEB-INF、web.xml 二、使用外部Tomcat 三、测试是否支持jsp controller ...