1. 程式人生 > >SpringMVC系列(十五)Spring MVC與Spring整合時實例被創建兩次的解決方案以及Spring 的 IOC 容器和 SpringMVC 的 IOC 容器的關系

SpringMVC系列(十五)Spring MVC與Spring整合時實例被創建兩次的解決方案以及Spring 的 IOC 容器和 SpringMVC 的 IOC 容器的關系

問題 nbsp frame ota 展示 not als pri exc

一、Spring MVC與Spring整合時實例被創建兩次的解決方案

1.問題產生的原因

Spring MVC的配置文件和Spring的配置文件裏面都使用了掃描註解<context:component-scan base-package="com.study.springmvc" />

2.解決方案

2.1. 使 Spring 的 IOC 容器掃描的包和 SpringMVC 的 IOC 容器掃描的包沒有重合的部分,把Handler和service/DAO放在不同的包下
2.2. 使用 exclude-filter 和 include-filter 子節點來規定只能掃描的註解

springmvc.xml的配置,限制只掃描Handle的註解@Controller和異常處理的註解@ControllerAdvice

1 <context:component-scan base-package="com.study.springmvc" use-default-filters="false">
2         <context:include-filter type="annotation" 
3             expression="org.springframework.stereotype.Controller"/>
4         <context:include-filter type="annotation" 
5             expression
="org.springframework.web.bind.annotation.ControllerAdvice"/> 6 </context:component-scan>

spring的配置,限制不掃描Handle的註解@Controller和異常處理的註解@ControllerAdvice

1 <context:component-scan base-package="com.study.springmvc">
2         <context:exclude-filter type="annotation" 
3             expression
="org.springframework.stereotype.Controller"/> 4 <context:exclude-filter type="annotation" 5 expression="org.springframework.web.bind.annotation.ControllerAdvice"/> 6 </context:component-scan>

二、Spring 的 IOC 容器和 SpringMVC 的 IOC 容器的關系

SpringMVC 的 IOC 容器中的 bean 可以來引用 Spring IOC 容器中的 bean,反之不行,原因是:

1.Spring MVC是Spring的子類,子類可以引用父類,父類不能引用子類

2. 從軟件層面上來說,Spring MVC是展示層可以調用業務層,業務層不能調用展示層

SpringMVC系列(十五)Spring MVC與Spring整合時實例被創建兩次的解決方案以及Spring 的 IOC 容器和 SpringMVC 的 IOC 容器的關系