前段時間有人問我,為什么一定要在web.xml中配置spring的listener呢?
<listener>
<description>spring監聽器</description>
<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初始化時創建的。
----------------------------------------------------------------------------------------------------------------------------------------------
Spring和springMVC父子容器的關系
邏輯分析可知:
1,Spring容器的啟動是先於SpringMVC容器的,所以spring容器是不知道springMVC容器的存在的。也就是說父容器無法使用子容器的bean。
2,當父容器初始化好之后,會將自己放到servletcontext的屬性中:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
那么,子容器在初始化時,就能得到父容器的存在。子容器可以使用父容器的bean。
為什么Controller注冊在父容器中,<mvc:annotation-driver/>注冊在子容器中時,springMVC無法處理請求呢?
答:RequestMappingHandleMapping在找controller時,默認是不會從父容器中找的。所以我們可以手動的配置它從父容器找。但是這樣針對特定的HandlerMapping配置不好。
可以配置controller使用子容器裝載。這樣既分工明確,又可以免於配置。