Spring和SpringMVC父子容器关系初窥
整合Spring时Service层为什么不做全局包扫描详解
Spring与SpringMVC的容器关系分析
关于SpringMVC和Spring容器之间的关系,网上大佬们的分析已经很多了,下面我自己再总结一下。
在web.xml中通过监听器加载的配置文件applicationContext即为父容器,是最先被加载的。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xml param-value>
context-param>
如果在applicationContext中设置全局包扫描,所有注解的类都会实例到父容器中(@Controller/@Service/@@Repository/@Component)
<context:annotation-config>context:annotation-config>
<context:component-scan base-package="com.zjweu">context:component-scan>
在web监听器加载完主配置文件后,会开始加载servlet,而加载SpringMVC的DispatcherServlet时,会扫描springmvc.xml配置文件,加载完后相当于在spring父容器中新划分了一块区域,只属于springmvc的区域,我们称之为子容器。
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
子容器的几个特点:
现在我们在子容器springmvc.xml中不配置包扫描,然后在controller层编写代码
@Controller
public class HelloWorld {
@RequestMapping("/hello")
public String hello(){
return "main";
}
}
我们发现浏览器测试时会报404,为什么?
按照子容器的特点来看:子容器不是能够访问到父容器的所有bean吗,在父容器配置了全局注解扫描,按照道理来说controller层的helloworld类应该能访问到的,可事实上并不行。
原因在于:SpringMVC初始化时,只会寻找SpringMVC这个子容器中的所有使用了@Controller注解的Bean,来确定其是否是一个handler。并不会关注父容器中是否已注册了这个bean,而我们在使用注解 @Autowired
时,子容器在发现容器中没有对应类的时候,才会去父容器中查找,再注入。
因此,在做SSM整合时,建议使用父容器扫描全局并且排除@Controller注解
<context:component-scan base-package="com.zjweu">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
而在springmvc配置文件仅扫描controller层
<context:component-scan base-package="com.zjweu.controller">context:component-scan>
当然,将全局扫描只配置在springmvc子容器中,父容器不配置扫描,也不会报错
这里涉及一些性能的问题,你们可以自行百度
<context:component-scan base-package="com.zjweu">context:component-scan>