spring脚手架原理

文章目录
  1. 1. spring通过web xml作为入口加载contextConfigLocation
    1. 1.1. ContextLoaderListener 与DispatcherServlet
    2. 1.2. 1.利用ContextLoaderListener (实现ServletContextListener)
    3. 1.3. 2.或者ContextLoaderServlet(采用load-on-startup Servlet 实现)

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.

spring-context1

所以Listener会创建appplication context,dispatcherservlet也会创建application context。

dispatcherservlet流程:

1
2
3
4
5
6
client -> 
DispatcherServlet -> HandlerMapping ->
DispatcherServlet -> handlerAdapter ->
DispatcherServlet -> modelandview ->
DispatcherServlet -> viewresolver ->
DispatcherServlet -> model -> view

1.利用ContextLoaderListener (实现ServletContextListener)

在创建时自动查找WEB-INF/ 下的applicationContext.xrnl 文件。

可以用contextConfigLocation指定文件地址

1
2
3
4
5
6
7
8
9
10
11
12
13
<web-app>
  <!一确定多个配置文件>
  <context-param>
    <!-- 参数名为contextConfigLocation -->
    <param-name> contextConfigLocation </param-name>
    <!一多个配置文件之间以,隔开二〉
    <param-value>/WEB-工NF/daoContext.xml,/WEB-INF/applicationContext.xml</param-value>
  </context-param>
  <!-- 采用listener创建ApplicationContext 实例-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

2.或者ContextLoaderServlet(采用load-on-startup Servlet 实现)

该Servlet 在启动时,会自动查找WEB-IN日下的applicationContext. xml 文件。

当然,为了让ContextLoaderServlet 随应用启动而启动,应将此Servlet 配置成load-on-startup 的Servleto load-on-startup 的值小一点比较合适,因为要保证ApplicationContext 优先创建。

1
2
3
4
5
<servlet>
  <servlet-name>context</servlet-arne>
    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>