Spring 與 SpringMVC 容器父子關係引出的相應問題

1)關係說明

spring 與 springmvc 父子關係:spring (父容器),springmvc (子容器)

springmvc(子)--- 可調用 --> spring(父) 中的 bean,屬性值等
但 spring(父)-- 不可調用 --> springmvc(子) 中的 bean,屬性值等

2)配置原則

spring-context.xml
<!-- 啓動組件掃描,排除@Controller的組件,因爲控制器組件由SpringMVC配置文件掃描 -->
<context:component-scan base-package="com.***.***">
   <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

springmvc.xml
<!-- 自動掃描該包,使SpringMVC認爲包下用了@controller註解的類是控制器,要有use-default-filters="false" -->
<context:component-scan base-package="com.***.***.controller" >
   <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

success:
url --> servlet --> springmvc(訪問 controller,所以 controller 必須放到springmvc容器)
springmvc --> spring(controller 調用 service,dao)

error:
把 controller 放到 spring 容器,不放到 springmvc 出現的問題:
url --> servlet --> springmvc(spring 會將掃描的對象都會存放到 spring 的容器,而不會放到 springmvc 子容器中,當訪問項目的時候,springmvc 通過處理器映射器找不到和其對應的 Controller,報 404 錯誤! )

spring 容器不掃描,全部放到 springmvc 中掃描出現的問題: 
在裏面可以同時掃描 controller層、service層、dao層 的註解,但是,子容器controller 進行掃描裝配時裝配了 @Service註解 的實例,而該實例理應由父容器進行初始化以保證事務的增強處理(因爲事務管理器是配置在 spring 容器中的),所以此時得到的將是原樣的 Service(沒有經過事務加強處理,沒有事務處理能力,無法訪問到事務對象,導致事務失效)

@Value("${name}") 取不到 properties 文件中定義的變量值
<!-- 配置文件引入 -->
<context:property-placeholder location="classpath:application.properties" 
                       ignore-resource-not-found="true" ignore-unresolvable="true" />
service,dao 中不能 @Value 配置在 springmvc.xml 的properties (父容器 -- 不能訪問 --> 子容器 的東西)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章