a13698822086 发表于 2017-2-8 09:28:31

tomcat启动时Spring做了什么(一、创建ContextLoader)

在配置Spring 的时候,我们需要在web.xml文件中配置一个listener如下:
<listener>
<listener-class>
    org.springframework.web.context.ContextLoaderListener
         </listener-class>
</listener>
当server启动的时候,需要初始化WebApplicationContext,那么就会调用ContextLoaderListener的contextInitialized方法,该方法如下:
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
首先,它将创建ContextLoader;
那么在创建ContextLoader的时候会干什么呢?在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());
}
}
事实上,此段静态代码是为了获取WebApplicationContext的实现,WebApplicationContext的策略是定义在一个叫做ContextLoader.properties的文件中,Spring给了默认的定义,内容如下:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
一般来说,Spring团队建议不要去修改它,直接使用即可。
获取ContextLoader.properties的classPath后,将它用Properties包装。
接下来就是初始化WebApplicationContext了。
(待续)
页: [1]
查看完整版本: tomcat启动时Spring做了什么(一、创建ContextLoader)