以Tomcat举例,启动Tomcat之后,首先会加载web.xml文件:
容器首先读取web.xml中的的配置内容和标签中配置项;紧接着实例化ServletContext对象,并将配置的内容转化为键值传递给ServletContext;创建配置的监听器的类实例,并且启动监听;随后调用listener的contextInitialized(ServletContextEvent args)方法,ServletContext = ServletContextEvent.getServletContext();此时你可以通过ServletContext获取context-param配置的内容并可以加以修改,此时Tomcat还没完全启动完成。后续加载配置的各类filter;最后加载servlet;最后的结论是:
web.xml中配置项的加载顺序是context-param=>listener=>filter=>servlet,配置项的顺序并不会改变加载顺序,但是同类型的配置项会应该加载顺序,servlet中也可以通过load-on-startup来指定加载顺序。
在spring,springmvc中有两种配置方式
一:
<!--Spring ApplicationContext 载入 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>seckill-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置springMVC需要加载的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml Mybatis - > spring -> springmvc --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-*.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>seckill-dispatcher</servlet-name> <!-- 默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping>二:
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/classes/applicationContext*.xml</param-value> </context-param> <servlet> <description>spring mvc servlet</description> <servlet-name>springMvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <description>spring mvc 配置文件</description> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>1,Spring容器的启动是先于SpringMVC容器的,所以spring容器是不知道springMVC容器的存在的。也就是说父容器无法使用子容器的bean。
2,当父容器初始化好之后,会将自己放到servletcontext的属性中:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
那么,子容器在初始化时,就能得到父容器的存在。子容器可以使用父容器的bean。
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>这个listener是告诉容器,启动的时候创建spring容器,并加载我们在context-param中配置的contextConfigLocation对应的配置文件的bean。
那么这一步是必须的吗?如果把这个listener注释掉,发现启动项目后报错。
原因:springMVC容器中的bean使用到spring容器中的bean。如果两个容器之间的bean没有关联,则不会报错。
可以在spring-mvc.xml中import spring.xml,发现启动就不会报错
<import resource="spring.xml"/>最后的结论是:使用spring容器的目的,我认为就是为了区分哪些bean是可以脱离web环境使用的。
注:springmvc的容器创建是在DispatchServlet初始化时创建的。
参考:
https://www.cnblogs.com/ljdblog/p/7461854.html https://blog.csdn.net/lexang1/article/details/52231492(加上拦截器)
