Spring源码-父子容器
什么是IOC容器?
最主要是完成了完成对象的创建和依赖的管理注入等等。
Spring的容器主要用途?
在Spring整体框架的核心概念中,容器是核心思想,就是用来管理Bean的整个生命周期的,而在一个项目中,容器不一定只有一个,Spring中可以包括多个容器,而且容器有上下层关系。
Spring父子容器流程图
Spring父子容器源代码分析
首先,我们先看看web.xml中常用的核心配置。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-core.xml</param-value>
</context-param>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-dispatcher.xml</param-value>
</init-param>
<init-param>
<param-name>detectAllHandlerMappings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
上面xml配置包含了一个监听器ContextLoaderListener,一个父容器配置Bean的配置文件applicationContext-core.xml和一个Servlet DispatcherServlet,它们之间的关系在父子关系流程图中已经介绍。
在源码中,父容器调用的是ContextLoaderListener#contextInitialized。
// 父容器初始化
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
子容器Servlet调用的是FrameworkServlet#initServletBean。
@Override
protected final void initServletBean() throws ServletException {
// 子容器初始化
this.webApplicationContext = initWebApplicationContext();
initFrameworkServlet();
}
父子容器在创建的时候都调用了同一个initWebApplicationContext方法。
其实在FrameworkServlet#initWebApplicationContext方法内存在如下的父子容器关系。
protected WebApplicationContext initWebApplicationContext() {
// 父容器
WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
// 当前容器
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
// 是否存在父容器
if (cwac.getParent() == null) {
// 给子容器设置父容器
cwac.setParent(rootContext);
}
configureAndRefreshWebApplicationContext(cwac);
}
}
}
}
由上图可以得出在Spring如果存在多个容器,多个容器是存在父子关系的,而父子关系重要的一点就是:父容器不可见子容器注册的Bean,子容器是可见父容器的Bean。