首先 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