当前位置: 代码迷 >> J2EE >> 关于springmvc事务管理配置的有关问题
  详细解决方案

关于springmvc事务管理配置的有关问题

热度:29   发布时间:2016-04-17 23:10:54.0
关于springmvc事务管理配置的问题
我现在这个项目以前的同事是用的配置bean的方式配置的service,结构是controller-service-dao,以为太麻烦了,写controller和serv都要去配置文件配置一遍,我现在想改成注解方式来写(之前有过一点注解开发经历,只是对配置和底层的东西不太清楚),我
把 @Transactional(propagation= Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)放在service层,故意做了两次去dao层操作数据库,一次是添加数据,一次让他报错,结果测试了一下没有效果,事务并没有回滚,数据还是添加进去了,但是我把@Transactional(propagation= Propagation.REQUIRED, readOnly = true, rollbackFor = Exception.class)放在dao层(操作数据库的地方),也是做两次操作,竟然事务回滚了。网上寻找了很多答案,都不奏效,请问我应该怎么把事务配置在service层做事务管理呢。
------解决思路----------------------
使用注解配置事务的步骤:
1. 在beans.xml中导入tx/aop命名空间约束
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd">
2. 在beans.xml中配置一个事务管理器
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
3. 配置一个事务的注解驱动
<tx:annotation-driven transaction-manager="txManager"/>
4. 在Service类上加入事务注解 @Transactional,当前类中的所有方法都是一个事务
5. 直接从spring工厂中获取一个代理对象操作
AccountService proxy = (AccountService)ctx.getBean("accountService");

配置好后测试吧,只要类中有个方法报错,整个事务回滚。
  相关解决方案