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
来源: http://www.bubuko.com/infodetail-3297776.html