分享

解决spring事务annotation未成功

 昵称15157082 2013-12-19

1、问题复现

     spring 3.0 + hibernate 3.2

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

     事务配置使用

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

 

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

2、问题检查

     当修改dao层实现逻辑为:

Java代码  收藏代码
  1. Assert.notNull(entity, "entity不能为空");  
  2. Transaction ts = getSession().beginTransaction();  
  3. getSession().saveOrUpdate(entity);  
  4. getSession().flush();  
  5. ts.commit();  
  6. logger.debug("save entity: {}", entity);  

 

   可以正常提交插入、更新。确定为事务未提交。

3、问题分析

    spring mvc使用注解方式时需要使用

Xml代码  收藏代码
  1. <context:component-scan base-package="com.fengzhiyin" />  

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

    当

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

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

4、问题解决

将spring mvc中扫描controller的context:component分成两部分,将扫描其他目录的context:component放入application.xml文件中(该文件为)org.springframework.web.context.ContextLoaderListener的加载文件。

如下配置:

Xml代码  收藏代码
  1. <!-- spring mvc 配置文件 -->  
  2. <context:component-scan base-package="com.fengzhiyin.controller" />  

 和

Xml代码  收藏代码
  1. <!-- spring context配置文件 -->  
  2. <context:component-scan base-package="com.fengzhiyin.">  
  3.     <context:exclude-filter type="regex" expression=".*Controller$" />  
  4. </context:component-scan>  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多