Spring IOC 容器的启动与销毁

 AbstractApplicationContext 是一个抽象类,IOC 容器的启动和销毁分别始于它的 refresh 和 doClose 方法。

Web 项目中,web.xml 中配置如下:

<context-param>     <param-name>contextConfigLocation</param-name>     <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml</param-value> </context-param> <listener>     <listener-class>          org.springframework.web.context.ContextLoaderListener     </listener-class> </listener>

ContextLoaderListener 用来监听 ServletContext 的生命周期,由于 ServletContext 代表应用本身,因此可以说 Web 应用的启动和销毁,分别触发了 Spring IOC 容器的启动和销毁。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {      //初始化 web 容器     @Override     public void contextInitialized(ServletContextEvent event) {         //初始化 IOC 容器         initWebApplicationContext(event.getServletContext());     }      //关闭 web 容器     @Override     public void contextDestroyed(ServletContextEvent event) {         //关闭 IOC 容器         closeWebApplicationContext(event.getServletContext());         ContextCleanupListener.cleanupAttributes(event.getServletContext());     }  }

initWebApplicationContext 方法做了以下几件事:

  1. 创建 WebApplicationContext 对象,这个对象的类型默认为 XmlWebApplicationContext(来自于ContextLoader.properties)。
  2. 设置配置文件的位置 wac.setConfigLocation(configLocationParam),这个配置从 web.xml 中读取。
  3. 执行 AbstractApplicationContext 的 refresh 方法,启动 IOC 容器。

closeWebApplicationContext 方法,会执行 AbstractApplicationContext 的 doClose 方法。https://www.cnblogs.com/xmsx/p/9776346.html

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信