本文轉載自 http://www.javashuo.com/article/p-ukkbdhdl-eg.htmlhtml
說到spring和springmvc,其實有不少工做好多年的人也分不清他們有什麼區別,若是你問他項目裏用的什麼MVC技術,他會說咱們用的spring和mybatis,或者spring和hibernate。web
在潛意識裏會認爲springmvc就是spring,以前我也是這麼認爲的,哈哈。 spring
雖然springMVC和spring有必然的聯繫,可是他們的區別也是有的。下面我就簡單描述下express
首先 springmvc和spring它倆都是容器,容器就是管理對象的地方,例如Tomcat,就是管理servlet對象的,而springMVC容器和spring容器,就是管理bean對象的地方,再說的直白點,springmvc就是管理controller對象的容器,spring就是管理service和dao的容器,這下你明白了吧。因此咱們在springmvc的配置文件裏配置的掃描路徑就是controller的路徑,而spring的配置文件裏天然配的就是service和dao的路徑spring-mvc
spring-mvc.xmlmybatis
<context:component-scan base-package="com.smart.controller" />
applicationContext-service.xmlmvc
<!-- 掃描包加載Service實現類 --> <context:component-scan base-package="com.smart.service"></context:component-scan>
或者
<context:component-scan base-package="com.smart">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
至於他是怎麼管理起來的,又是怎麼注入屬性的,這就涉及到他們底層的實現技術了
其次, spring容器和springmvc容器的關係是父子容器的關係。spring容器是父容器,springmvc是子容器。在子容器裏能夠訪問父容器裏的對象,可是在父容器裏不能夠訪問子容器的對象,說的通俗點就是,在controller裏能夠訪問service對象,可是在service裏不能夠訪問controller對象app
因此這麼看的話,全部的bean,都是被spring或者springmvc容器管理的,他們能夠直接注入。而後springMVC的攔截器也是springmvc容器管理的,因此在springmvc的攔截器裏,能夠直接注入bean對象。hibernate
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/employee/**" ></mvc:mapping> <bean class="com.smart.core.shiro.LoginInterceptor" ></bean> </mvc:interceptor> </mvc:interceptors>
而web容器又是什麼鬼,
web容器是管理servlet,以及監聽器(Listener)和過濾器(Filter)的。這些都是在web容器的掌控範圍裏。但他們不在spring和springmvc的掌控範圍裏。所以,咱們沒法在這些類中直接使用Spring註解的方式來注入咱們須要的對象,是無效的,
web容器是沒法識別的。code
但咱們有時候又確實會有這樣的需求,好比在容器啓動的時候,作一些驗證或者初始化操做,這時可能會在監聽器裏用到bean對象;又或者須要定義一個過濾器作一些攔截操做,也可能會用到bean對象。
那麼在這些地方怎麼獲取spring的bean對象呢?下面我提供兩個方法:
一、
public void contextInitialized(ServletContextEvent sce) { ApplicationContext context = (ApplicationContext) sce.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); UserService userService = (UserService) context.getBean("userService"); }
二、
public void contextInitialized(ServletContextEvent sce) { WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); UserService userService = (UserService) webApplicationContext.getBean("userService"); }
注意:以上代碼有一個前提,那就是servlet容器在實例化ConfigListener並調用其方法以前,要確保spring容器已經初始化完畢!而spring容器的初始化也是由Listener(ContextLoaderListener)完成,所以只需在web.xml中先配置初始化spring容器的Listener,而後在配置本身的Listener。