在编写spring web项目中遇到的一些问题。DispatcherServlet 和ContextLoaderListener的关系。
加载顺序 ContextLoaderListener -> DispatcherServlet
DispatcherServlet :负责加载controller对象,视图解析器等。
ContextLoaderListener : 负责加载service,dao,component以及开启定时任务,注册数据库配置等等。
为了避免controller被初始化两次的问题,一定要注意这几个配置文件的编写。将controller的自动扫描至配置在dispatcher.xml的文件当中
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:conf/spring-context.xml;classpath:conf/spring-mybatis.xml;
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springMVC核心配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
spring加载过程中加载了两个容器。
2017-09-19 11:54:12.069:INFO:oejs.Server:main: jetty-9.2.6.v20141205
2017-09-19 11:54:15.468:INFO:/route:main: No Spring WebApplicationInitializer types detected on classpath
2017-09-19 11:54:15.993:INFO:/route:main: Set web app root system property: 'topo' = [F:\zhongyingProject-websocket\toposerver\webapp]
2017-09-19 11:54:16.010:INFO:/route:main: Initializing log4j from [classpath:conf/log4j.properties]
2017-09-19 11:54:16.014:INFO:/route:main: Initializing Spring root WebApplicationContext
启动topoServer程序
2017-09-19 11:54:17.005:INFO:/route:main: $Id: GZIPFilter.java,v 1.15 2005/03/12 01:52:29 mike Exp $
2017-09-19 11:54:17.005:INFO:/route:main: [ERROR] Could not locate the filter config file: tk-filters.properties
2017-09-19 11:54:17.005:INFO:/route:main: ?GZIPFilter.Enabled: false
2017-09-19 11:54:17.005:INFO:/route:main: ?GZIPFilter.LogStats: false
2017-09-19 11:54:17.006:INFO:/route:main: $Id: CacheHeaderFilter.java,v 1.10 2005/03/12 01:52:28 mike Exp $
2017-09-19 11:54:17.006:INFO:/route:main: [ERROR] Could not locate the filter config file: tk-filters.properties
2017-09-19 11:54:17.006:INFO:/route:main: ?CacheFilter: false
2017-09-19 11:54:17.006:INFO:/route:main: ?CacheFilter.ExpirationMinutes: -1
2017-09-19 11:54:17.056:INFO:/route:main: Initializing Spring FrameworkServlet 'spring'
由上面可见,加载了Spring root WebApplicationContext和Spring FrameworkServlet ‘spring’。。
对于以下代码
public class TopoServerStart implements ApplicationListener<ContextRefreshedEvent> {
/**
* 监听,servlet容器启动完成之后就可以起动数据进行缓存数据
*/
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){
//root application context 没有parent,他就是老大.
//需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
System.out.println("启动topoServer程序");
}
}
}
这段代码是在初始化完Spring root WebApplicationContext之后执行的。。
因此会导致这段代码执行之后,spring还在初始化controller。如果要在controller中操作一些方法,则需要考虑清楚在进行。