码迷,mamicode.com
首页 > 编程语言 > 详细

Spring容器启动过程

时间:2017-05-27 14:21:05      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:spring启动

搞了一年多的Java了,每个项目都在用Spring,这几天没事看了看Spring源码,总结了下Spring容器的启动过程,想把它记录下来,免得忘了


spring容器的启动方式有两种:

1、自己提供ApplicationContext自己创建Spring容器

2、Web项目中在web.xml中配置监听启动

org.springframework.web.context.ContextLoaderListener


先介绍第一种(自创建)

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml")
User user = (User) context.getBean()}

当通过ClassPathApplicationContext初始化容器时,它会根据定位加载spring.xml配置,然后解析配置文件,生成Bean,注册Bean,最后我们在通过getBean获取对象,这一现象就跟IOC容器的初始化过程一样,资源定位、资源加载、资源解析、生成Bean、Bean注册


我们再来说说第二种初始化方式:

第二种在web.xml文件中进行配置,根据web容器的启动而启动

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

ContextLoaderListener实现了ServletContextListener接口,实现了两个方法

//初始化WebApplicationContext容器
public void contextInitialized(ServletContextEvent event) {
    this.initWebApplicationContext(event.getServletContext());
}

//销毁WebApplicationContext容器
public void contextDestroyed(ServletContextEvent event) {
    this.closeWebApplicationContext(event.getServletContext());
    ContextCleanupListener.cleanupAttributes(event.getServletContext());
}

参数ServletContextEvent能直接获取servletContext也就是java web容器的上下文

在父类中调用了intitWebApplicationContext方法,传入了ServletContext,在父类方法中对ServletContext进行了判断,检测servletContext的属性中是否存在spring的根上下文属性如果存在则是错误的,因为表明已经有一个根上下文已经启动,再启动会冲突,所以避免重复启动!

(servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != ) {
    IllegalStateException()}


本文出自 “项以奇的博客” 博客,请务必保留此出处http://12854546.blog.51cto.com/12844546/1930134

Spring容器启动过程

标签:spring启动

原文地址:http://12854546.blog.51cto.com/12844546/1930134

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!