spring4整合hibernate4事務不生效問題
阿新 • • 發佈:2019-01-29
在主容器中(applicationContext.xml),將Controller的註解排除掉
<context:component-scan base-package="com.feng.controller">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
而在springMVC配置檔案中將Service註解給去掉
<context:component-scan base-package="com.feng">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
因為spring的context是父子容器,所以會產生衝突,由ServletContextListener產生的是父容器,springMVC產生的是子容器,子容器Controller進行掃描裝配時裝配了@Service註解的例項,而該例項理應由父容器進行初始化以保證事務的增強處理,所以此時得到的將是原樣的Service(沒有經過事務加強處理,故而沒有事務處理能力。
還有一種方式是將service層改用xml配置,其實這樣做也是變相的讓springmvc無法掃描service,而只能依賴父視窗也就是ServletContextListener來進行初始化,這樣同樣被賦予了事務性。
<context:component-scan base-package="com.feng.controller">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
而在springMVC配置檔案中將Service註解給去掉
<context:component-scan base-package="com.feng">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service" />
</context:component-scan>
因為spring的context是父子容器,所以會產生衝突,由ServletContextListener產生的是父容器,springMVC產生的是子容器,子容器Controller進行掃描裝配時裝配了@Service註解的例項,而該例項理應由父容器進行初始化以保證事務的增強處理,所以此時得到的將是原樣的Service(沒有經過事務加強處理,故而沒有事務處理能力。
還有一種方式是將service層改用xml配置,其實這樣做也是變相的讓springmvc無法掃描service,而只能依賴父視窗也就是ServletContextListener來進行初始化,這樣同樣被賦予了事務性。