首页 > 学院 > 开发设计 > 正文

Spring源码之ContextLoaderListener(1)

2019-11-06 07:39:34
字体:
来源:转载
供稿:网友

容器(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.XmlWebApplicationContextpublic 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()); //获取WebApplicationContext实例return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass); }

总结: 第一步:读取Spring自己的默认配置 ContextLoader.properties,获取WebApplicatiotContext实例 ①、tomcat启动读取web.xml的Listener ②、ContextLoader的静态代码块读取ContextLoader.properties文件获取XmlWebApplicationContext ③、从②读取配置得到xmlWebApplicatoinContext 通过反射获取WebApplicationContext对象

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

第三步: 将WebApplicationContext放入到ServletContext中


上一篇:NOIP2009

下一篇:设计模式之适配器模式

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表