SpringMVC和Spring整合的目的;分工明确;
SpringMVC的配置文件就来配置和网站转发逻辑以及网站功能有关的(视图解析器,文件上传解析器,支持ajax,xxx);springmvc.xml
Spring的配置文件来配置和业务有关的(事务控制,数据源,xxx);spring.xml
1. <import resource="spring.xml"/>:可以合并配置文件;虽然是两个spring配置文件,但这种方式仍然相当于一个ioc
2.规范整合
分容器,即两个ioc
1)、在web.xml已经配置SpringMVC的基础上,添加spring容器到web.xml
注意:我们之前配置spring到xml那是一个java项目,并没有web.xml
<!-- needed for ContextLoaderListener --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
2)、防止两个容器中的组件(只要加注解的组件会被容器创建),被重复创建
SpringMVC.xml与Spring.xml分别加代码
因为Spring管理业务逻辑组件;
排除扫描Controller组件
<context:component-scan base-package="com.atguigu"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
因为SpringMVC管理控制器组件;
只扫描Controller组件 要禁用默认行为
<context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
3)、注意子父容器问题
Spring是一个父容器,SpringMVC是一个子容器;
子容器还可以引用父容器的组件;
父容器不能引用子容器的组件;
注意调用方式,按正常的调用方式即可Controller调Service
原文:https://www.cnblogs.com/yanl55555/p/11906782.html