spring通过web xml作为入口加载contextConfigLocation
ContextLoaderListener 与DispatcherServlet
你要和Web搞上关系,无非就是那么几种,监听器、过滤器和Servlet,最终都是为了切进ServletContext。
SpringMVC是基于Servlet的,直接配个Servlet不就行了嘛。below is the reason:有很多插件都是通过listener注入的。servlet专注于步骤更好。
There is a list to understand ApplicationContexts and WebApplicationContexts
a. Application-Contexts are hierarchial and so are WebApplicationContexts. Refer documentation here
b. ContextLoaderListener creates a root web-application-context for the web-application and puts it in the ServletContext. This context can be used to load and unload the spring-managed beans ir-respective of what technology is being used in the controller layer(Struts or Spring MVC).
c. DispatcherServlet creates its own WebApplicationContext and the handlers/controllers/view-resolvers are managed by this context.
**d. When ContextLoaderListener is used in tandem with DispatcherServlet, a root web-application-context is created first as said earlier and a child-context is also created by DispatcherSerlvet and is attached to the root application-context. **Refer documentation here.
Refer to the diagram below from the Spring documentation.
所以Listener会创建appplication context,dispatcherservlet也会创建application context。
dispatcherservlet流程:
1 | client -> |
1.利用ContextLoaderListener (实现ServletContextListener)
在创建时自动查找WEB-INF/ 下的applicationContext.xrnl 文件。
可以用contextConfigLocation指定文件地址
1 | <web-app> |
2.或者ContextLoaderServlet(采用load-on-startup Servlet 实现)
该Servlet 在启动时,会自动查找WEB-IN日下的applicationContext. xml 文件。
当然,为了让ContextLoaderServlet 随应用启动而启动,应将此Servlet 配置成load-on-startup 的Servleto load-on-startup 的值小一点比较合适,因为要保证ApplicationContext 优先创建。
1 | <servlet> |