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

Spring源码之ContextLoaderListener(1)

2017-03-04 15:49 302 查看
容器(tomcat)在启动时会读取web.xml中listener

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


说白了就是一个ServletContextListener所以在容器(tomcat)启动的Listener会被初始化,并且执行contextInitized(ServletEvent event)方法,所以主要看如下两个部分代码:

初始化ServletContextListener

contextInitialized(ServletContextEvent even)执行

初始化ServletContextListener所以如下静态代码块会被执行

Properties defaultStrategies =  null;
static {
try {
ClassPathResource ex = new ClassPathResource("ContextLoader.properties", ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(ex);
} catch (IOException var1) {
throw new IllegalStateException("Could not load \'ContextLoader.properties\': " + var1.getMessage());
}

currentContextPerThread = new ConcurrentHashMap(1);
}


看到没有就是读取ContextLoader.properties的配置文件文件中就一行配置key=value如下所示:

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext


public void contextInitialized(ServletContextEvent event) {        this.initWebApplicationContext(event.getServletContext());
}


注意:ContextLoaderListener的父类ContextLoader就是这里的上面代码的this

即ContextLoader.initWebApplicationContext(ServletContext)

该方法主要做了如下几个事情:

//读取ContextLoader.properties获取XmlWebApplicationContext
//通过反射获取webApplicationContext实例
this.context = this.createWebApplicationContext(servletContext);
//加载配置文件(最关键的、最复杂部分)
this.configureAndRefreshWebApplicationContext(err, servletContext);
//将WebApplicationContext放入到ServletContext中
servletContext.setAttribute("org.springframework.web.context.WebApplicationContext.ROOT", this.context);


protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//为了方便读者查看将部分代码的实现直接写到这里了
//读取配置文件
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
4000

//获取WebApplicationContext实例
return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
}


总结:

第一步:读取Spring自己的默认配置

ContextLoader.properties,获取WebApplicatiotContext实例

①、tomcat启动读取web.xml的Listener

②、ContextLoader的静态代码块读取ContextLoader.properties文件获取XmlWebApplicationContext

③、从②读取配置得到xmlWebApplicatoinContext

通过反射获取WebApplicationContext对象

第二步:

读取我们程序员指定的配置文件,比较复杂放到下一篇博文

第三步:

将WebApplicationContext放入到ServletContext中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 源码