spring容器和springmvc容器,以及web容器的關係

首先 springmvc和spring它倆都是容器,容易就是管理對象的地方,例如Tomcat,就是管理servlet對象的,而springMVC容器和spring容器,就是管理bean對象的地方,再說的直白點,springmvc就是管理controller對象的容器,spring就是管理service和dao的容器。 因此咱們在springmvc的配置文件裏配置的掃描路徑就是controller的路徑,而spring的配置文件裏天然配的就是service和dao的路徑web

spring-mvc.xmlspring

<context:component-scan base-package="com.smart.controller" />
applicationContext-service.xmlexpress

<!-- 掃描包加載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-mvc

spring容器和springmvc容易的關係是父子容器的關係。spring容器是父容器,springmvc是子容器。在子容器裏能夠訪問父容器裏的對象,可是在父容器裏不能夠訪問子容器的對象,說的通俗點就是,在controller裏能夠訪問service對象,可是在service裏不能夠訪問controller對象mvc

而web容器是管理servlet,以及監聽器(Listener)和過濾器(Filter)的。 這些都是在web容器的掌控範圍裏。但他們不在spring和springmvc的掌控範圍裏 。所以,咱們沒法在這些類中直接使用Spring註解的方式來注入咱們須要的對象,是無效的,web容器是沒法識別的。
 app

那麼在這些地方怎麼獲取spring的bean對象呢?下面提供兩個方法:component

一、xml

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"); 
}get

相關文章
相關標籤/搜索