前段时间有人问我,为何必定要在web.xml中配置spring的listener呢?web
<listener>
<description>spring监听器</description>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
自己咱们都知道,这个listener是告诉容器,启动的时候建立spring容器,并加载咱们在context-param中配置的contextConfigLocation对应的配置文件的bean。spring
那么这一步是必须的吗?若是把这个listener注释掉,发现启动项目后报错。spring-mvc
缘由:springMVC容器中的bean使用到spring容器中的bean。若是两个容器之间的bean没有关联,则不会报错。mvc
能够在spring-mvc.xml中import spring.xml,发现启动就不会报错app
<import resource="spring.xml"/>
结语:使用spring容器的目的,我认为就是为了区分哪些bean是能够脱离web环境使用的。this
注:springmvc的容器建立是在DispatchServlet初始化时建立的。spa
----------------------------------------------------------------------------------------------------------------------------------------------xml
逻辑分析可知:ip
1,Spring容器的启动是先于SpringMVC容器的,因此spring容器是不知道springMVC容器的存在的。也就是说父容器没法使用子容器的bean。servlet
2,当父容器初始化好以后,会将本身放到servletcontext的属性中:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
那么,子容器在初始化时,就能获得父容器的存在。子容器能够使用父容器的bean。
答:RequestMappingHandleMapping在找controller时,默认是不会从父容器中找的。因此咱们能够手动的配置它从父容器找。可是这样针对特定的HandlerMapping配置很差。
能够配置controller使用子容器装载。这样既分工明确,又能够免于配置。