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


一、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是展示層可以調用業務層,業務層不能調用展示層


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM