`

spring+springMVC,声明式事务失效,原因以及解决办法

阅读更多

一.声明式事务配置:

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1.   

 

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  2.     <property name="dataSource" ref="dataSource" />  
  3. </bean>  
  4.    <tx:advice id="txAdvice" transaction-manager="transactionManager">  
  5.    <tx:attributes>  
  6.          <tx:method name="add*" propagation="REQUIRED" read-only="false"/>  
  7.          <tx:method name="del*" propagation="REQUIRED" read-only="false"/>  
  8.          <tx:method name="get*" propagation="REQUIRED" read-only="true"/>  
  9.          <tx:method name="mod*" propagation="REQUIRED" read-only="false" />            
  10.    </tx:attributes>  
  11.    </tx:advice>  
  12.    <aop:config>     
  13.     <aop:pointcut id="serviceMethods" expression="execution(public * com.lexing.platform.service.*.*(..))" />  
  14.     <aop:advisor  advice-ref="txAdvice" pointcut-ref="serviceMethods"/>  
  15.    </aop:config>  


二.声明式事务失效,原因

 

 

根本原因:由子容器扫描装配了@Service 注解的实例。

spring的context是父子容器,由ServletContextListener 加载spring配置文件产生的是父容器,springMVC加载配置文件产生的是子容器,子容器对Controller进行扫描装配时装配了@Service注解的实例 (@Controller 实例依赖@Service实例),而该实例理应由父容器进行初始化以保证事务的增强处理,所以此时得到的将是原样的Service(没有经过事务加强处理,故而没有事务处理能力。

三.解决办法

1.spring配置文件applicationContext中:

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. <!-- 不扫描带有@Controller注解的类 ,让 springMVC 子容器加载。  
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. <context:component-scan base-package="com.lexing.platform">     
  2.     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>     
  3. </context:component-scan>    

 

 

2.springMVC配置文件 servlet-context.xml中

 

[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. <!-- 将 带有 @Service注解的类,交由spring 父容器实例化,[ @Service实例依赖@Repository实例,故spring父容器也会装配<span style="font-family: Arial, Helvetica, sans-serif;">@Repository 实例</span><span style="font-family: Arial, Helvetica, sans-serif;">]</span>  
[html] view plaincopy在CODE上查看代码片派生到我的代码片
 
 
  1. <context:component-scan base-package="com.lexing.platform">     
  2.     <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>     
  3. </context:component-scan>     
  4. 本文来源于:http://blog.csdn.net/z69183787/article/details/37819627
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics