本文转载自 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。