您的位置:首页 > 编程语言 > Java开发

Spring核心IOC容器实现分析

2016-01-15 23:17 483 查看
在Spring IOC容器的设计中,我们可以看到两个主要的容器系列,一个是实现BeanFactory接口的简单容器系列,这系列容器只实现了容器的最基本功能;另一个是ApplicationContext应用上下文,它作为容器的高级形态而存在。应用上下文在简单容器的基础上,增加了许多面向框架的特性,同时对应用环境做了许多适配。

单纯的这样说可能感觉比较抽象下面具体说一下,下面我们直接从实际代码中分析Spring IOC容器加载过程:

web.xml在Java Web中的作用类似于引导PC的引导程序,在应用启动的最开始进行加载,也是我们通常分析一个Web程序的入口

在下面的web.xml配置文件中主要做了两件事:

1、指定了spring的配置文件的位置,为下文Spring IOC容器初始化做准备,配置在这里,在Web启动的时候会加载到ServletContext上下文中

2、配置了ContextLoaderListener,主要监听什么呢?下文会做进一步解释

<?xml version="1.0" encoding="utf-8"?>
<web-app>
<!-- spring配置文件存放的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring.xml</param-value>
</context-param>

<!-- 配置spring启动listener入口 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>


下面我们打开ContextLoaderListener类看一下该类具体做了些什么

在这里我们可以看到ContextLoaderListener实现了ServletContextListener接口,该接口是Servlet基础接口,主要监听的就是Tomcat启动和销毁事件,实现的方法主要有两个:

1、ContextInitialized,该方法的入参或是监听的Event是ServletContextEvent事件,也就是Tomcat启动加载完web.xml会产生的是事件,ServletContextEvent持有了从web.xml加载的初始化配置的ServletContext上下文

2、ContextDestroyed,该方法的入参或是监听的Event是ServletContextEvent事件,在Tomcat关闭的时候执行该方法

由此,我们可以知道当Tomcat启动的时候加载web.xml文件的时候,会触发一个ServletContextEvent事件,进而会触发ContextLoaderListener类执行ContextInitialized方法,从源码中我们可以看出该方法中执行了initWebApplicationContext,入参为ServletContext。从这里开始,就开始进入ContextLoaderListener的父类ContextLoader(听名字就知道这才是真正初始化容器),执行ContextLoader的initWebApplicationContext,下面我们进入ContextLoader中继续查看初始化流程。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

public ContextLoaderListener() {
}
public ContextLoaderListener(WebApplicationContext context) {
super(context);
}
/**
* 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());
}
}


由上文可知,ContextLoader才是在为IOC容器初始化干活的人,在该类中执行了initWebApplicationContext(),该方法中首先查询了当前应用是否存在根容器,如果存在则报异常,否则的话则创建根容器,创建根容器的时候调用了一个方法determineContextClass,该方法主要就是为了确定该应用使用的是Spring IOC众多容器中的哪个容器,如果我们需要指定容器,那么可以在web.xml应用引导程序中配置初始化参数,指定具体的容器。当然如果不配置,该方法会去寻找默认的配置ContextLoader.properties,这里面指定了默认的容器类型是xmlWebApplicationContext。

容器创建完成之后,下面会执行一个重要的方法就是configureAndRefreshWebApplicationContext,在执行该方法时会将servletContext中获取的spring.xml的资源位置配置在已经创建的xmlWebApplicationContext中,然后执行容器的refresh()方法,这里才开始进入容器的初始化过程。

public class ContextLoader {

private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
private static final Properties defaultStrategies;
static {
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());
}
}

public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
}

Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();

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);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
}

if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
}

return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}

wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}

// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}

customizeContext(sc, wac);
wac.refresh();
}

protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}

/**
* Return the {@link ApplicationContextInitializer} implementation classes to use
* if any have been specified by {@link #CONTEXT_INITIALIZER_CLASSES_PARAM}.
* @param servletContext current servlet context
* @see #CONTEXT_INITIALIZER_CLASSES_PARAM
*/
protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>
determineContextInitializerClasses(ServletContext servletContext) {

List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes =
new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>();

String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM);
if (globalClassNames != null) {
for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) {
classes.add(loadInitializerClass(className));
}
}

String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM);
if (localClassNames != null) {
for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) {
classes.add(loadInitializerClass(className));
}
}

return classes;
}

}


这时候我们开始进入xmlWebApplicationContext的refresh方法,因为xmlWebApplicationContext间接继承了AbstractApplicationContext,所以xmlWebApplicationContext中可以执行refresh方法,而这里才是真正从加载spring.xml文件,并解析bean的开始,注册bean的开始。

下面我着重讲解下具体的执行流程(下面非重要代码已经省略):

1、prepareRefresh方法中主要记录了一些容器初始化时间等内容

2、obtainFreshBeanFactory,在这一步主要执行的是loadBeanDefinition。通过获取spring.xml配置文件的位置,然后使用BeanDefinitionReader进行加载,并通过SAX将spring.xml解析Document,并根据spring.xml中配置的bean解析出BeanDefinition,最终存在BeanDefinitionFactory中的一个Map中,HashMap的key是bean的id,value是类的全路径。

3、prepareBeanFactory做一些BeanFactory初始化的准备工作

4、finishBeanFactoryInitialization(预实例化bean),如果没有配置lazy-init,则spring bean的依赖注入将放在getBean的时候进行依赖注入,如果配置了lazy-init将在该方法内就完成依赖的注入过程

public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext, DisposableBean {@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) {
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;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: