项目场景:
在部署SpringMVC时遇到,以为是个小问题,解决后发现有一系列的问题值得研究.......
解决方案:
原因就是SpringMVC没有开启扫描,为什么这样说?或者说Spring容器和SpringMVC的容器关系没有过深入了解。
Spring是父容器,SpringMVC是其子容器,并且在Spring父容器中注册的Bean对于SpringMVC容器中是可见的,而在SpringMVC容器中注册的Bean对于Spring父容器中是不可见的,也就是子容器可以看见父容器中的注册的Bean,反之就不行。在这里就是所有带有@Controller注解的Bean都注册在Spring这个父容器中了,所以springMVC找不到处理器,不能进行跳转。
按照官方推荐根据不同的业务模块来划分不同容器中注册不同类型的Bean:Spring父容器负责所有其他非@Controller注解的Bean的注册,而SpringMVC只负责@Controller注解的Bean的注册,使得他们各负其责、明确边界。配置方式如下
1.在spring项目中spring.xml中配置:
<!-- Spring容器中注册非@controller注解的Bean -->
<context:component-scan base-package="com.hafiz.www">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
2.在springmvc项目中springmvc.xml中配置
<!-- SpringMVC容器中只注册带有@controller注解的Bean -->
<context:component-scan base-package="com.hafiz.www" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
不要让两个扫描有重叠。原因有如下几点:
- 扫描的类增多, 项目启动时间会延长
- @PostConstruct 注解标注的方法会执行2次
- 会使事务失效