1.引言
Spring作为一个IOC和AOP容器框架,使得依赖对象的创建由应用转移到了外部容器。然而,Spring是如何启动的?这是本文探索的内容。
2.Spring启动方式
Spring的启动方式有两种:
一是通过直接调用ClassPathXmlApplicationContext或其他继承了AbstractApplicationContext的类启动,如下图中ClassPathXmlApplicationContext、FileSystemXmlApplicationContext、XmlWebApplicationContext;
二是Web容器方式启动。
这两种方式启动Spring后,加载对象到容器的方式是一样的,核心都是通过调用AbstractApplicationContext的refresh方法。
本文主要介绍第二种方式,通过Web容器启动Spring,对BeanFactory的具体加载过程不做深入研究。
3.web.xml简介
Web容器一般都有一个web.xml。web.xml用于初始化配置信息,如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等。但web.xml在web容器中不是必须的,Servlet3.0使用注解代替了web.xml配置文件。Spring的web.xml文件如:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rootContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/res/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servletContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
其中context-param声明应用范围内的初始化参数。filter 过滤器元素将一个名字与一个实现javax.servlet.Filter接口的类相关联。listener 对事件监听程序的支持,事件监听程序在建立、修改和删除会话或servlet环境时得到通知,Listener元素指出事件监听程序类。servlet 在向servlet或JSP页面制定初始化参数或定制URL时,必须首先命名servlet或JSP页面,Servlet元素就是用来完成此项任务的。其中,加载配置的顺序为:context-param-->listener --> filter --> servlet。
当一个Web容器启动时,容器(Tomcat、JBoss等)会先读取web.xml配置文件中的配置,以这些配置为参数,创建一个ServletContext。此外,Web容器还会提供一个ServletContextListener 接口,Web容器在启动时会调用该接口的contextInitialized方法,容器退出时会调用该接口的contextDestroyed。Spring通过实现contextInitialized方法来完成启动操作。
4.Spring加载对象
分析Spring的Web容器启动,切入点就是上述提到的ServletContextListener ,contextInitialized方法是完成Spring启动的。web.xml配置信息中:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener是实现ServletContextListener接口的方法,我们接下来看ContextLoaderListener方法:
public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
......
/**
* Initialize the root web application context.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
/**
* Close the root web application context.
*/
@Override
public void contextDestroyed(ServletContextEvent event) {
closeWebApplicationContext(event.getServletContext());
ContextCleanupListener.cleanupAttributes(event.getServletContext());
}
}
其中,由ServletContextEvent会取得Web容器创建的ServletContext,initWebApplicationContext使用该ServletContext进行Spring加载。
完成以下工作:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
......
try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
......
return this.context;
}
......
}
其中,createWebApplicationContext用于获得WebApplicationContext的具体实现类,由resources目录下的ContextLoader.properties文件可已得到具体使用的实现类:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
该配置文件的加载是通过ContextLoader的静态代码块来实现的:
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
让我们把注意力再回到initWebApplicationContext方法,createWebApplicationContext返回的WebApplicationContext是XmlWebApplicationContext,
由上图可知,XmlWebApplicationContext实现了ConfigurableWebApplicationContext接口,因此,会在configureAndRefreshWebApplicationContext进行接下来的工作。
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
......
wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
......
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
wac.refresh();
}
wac.refresh()执行了XmlWebApplicationContext的refresh方法,refresh的最终实现类为AbstractApplicationContext,具体实现为:
@Override
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();
}
}
}
下面着重分析该方法。
5.AbstractApplicationContext.refresh
obtainFreshBeanFactory通知子类刷新内部的bean factory:
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
其中refreshBeanFactory用于加载子类中的配置,读取注册regular的beanDefinition。Spring中的实现类为AbstractRefreshableApplicationContext:
@Override
protected final void refreshBeanFactory() throws BeansException {
if (hasBeanFactory()) {
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);
}
}
接下来就是loadBeanDefinitions(beanFactory),该方法的实现类就是XmlWebApplicationContext,这样就回到了配置文件中配置的WebApplicationContext,
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}
至此,Web容器中的Spring已启动,接下来会进行Spring的对象加载和解析。
6.总结
- Spring的启动方式有两种:一是直接调用继承了AbstractApplicationContext的类启动,如ClassPathXmlApplicationContext、XmlWebApplicationContext等,二是使用Web容器启动。
- Spring的Web容器启动,主要在于实现了Web容器的ServletContextListener 接口,Web容器启动后会调用该接口的contextInitialized方法。这个过程中使用了观察者模式;