解决 spring mvc 3.+ 结合 hibernate3.+ 使用声明式事务没法提交的问题

  spring mvc使用注解方式;service使用@service注解 事务使用@Transactionaljava

     事务配置使用web

Java代码  
  1. <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  

     在插入或更新数据时,无报错,但数据库中无结果,而查询正常。疑为事务未提交。spring

 

方式用来扫描该包以及其子包下的@Controller注解的类,归入spring管理,而同时spring 容器也须要使用这种方式扫描包含@Service、@Components、@Required、@Autowired等注解用来管理bean和完成DI。数据库

   

Java代码  复制代码  收藏代码
  1. <context:component-scan base-package="com.yx.*" />  
 
  1. <context:component-scan base-package="com.yx.*" />  

 出如今spring mvc的配置文件中时,web 容器在扫描包含@Service或@Components的类并包含@Transaction是,此时@Transaction并为完成,致使事务未被注册。express

四、问题解决spring-mvc

分两部分扫描:mvc

spring-mvc.xml中扫描controllerapp

application.xml中扫描其余的ui

 

 

SpringMVC.xml配置文件--> 的只扫描controller组件 注意使用 use-default-filters="false" 
<context:component-scan base-package="com.yx.*" use-default-filters="false" > 
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan> 

ApplicationContext.xml配置文件-->扫描除controller外的全部组件 
<context:component-scan base-package="com.yx.*" > 
<context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
</context:component-scan>spa

 

经调试代码发现: 一、若是不设置use-default-filters="false",则Spring会扫描并优先注册默认的bean(固然包括标记为@Service的bean),这样,标记为@Transactional的service因为transaction manager还没有注册而未能生效,致使事务管理失效。 原理是:标记为@Transactional的service会wrap为通过transactional proxied(无论是CGLIB based或是JDK based)的bean,而再也不是纯的service; 

相关文章
相关标签/搜索