本地事务系列之五:使用Transactional注解

AOP的配置稍显复杂,通过[color=red]@Transactional[/color]注解,同样可以实现:

1. 在需要事务的类或方法上加[color=red]@Transactional[/color]:

如果是类上加注解,该类的所有public方法都会应用事务
如果是方法上加注解,该方法会应用事务。
在接口上加注解有风险,如果使用CGLIB(类代理)将不会启用事务。

2. 开启注解事务开关:[color=red]<tx:annotation-driven />[/color]

FruitShop实现:

public class AnnotationTxFruitShop extends JdbcDaoSupport implements FruitShop {

@Transactional // 可以设置传播级别、隔离级别、超时、只读、回滚策略
@Override
public boolean purchase(int fruitId, String userName, int count) {
// 此处和系列之四的AopTxFruitShop代码相同
}
}


beans-fruitshop-@.xml文件:

<tx:annotation-driven transaction-manager="txManager" />

<bean id="annotationTxFruitShop" class="com.john.tx.service.impl.AnnotationTxFruitShop">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- dataSource, txManager和之前的相同 -->


测试类和之前的类似:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/beans-fruitshop-@.xml" })
public class AnnotationTxFruitShopTest {

@Resource(name = "annotationTxFruitShop")
FruitShop annotationTxFruitShop;

@Test
public void test() {
...
}
}



附:
Spring底层也是通过AOP来实现对@Transactional注解事务的支持:
[img]http://dl2.iteye.com/upload/attachment/0099/7732/87027e38-ba94-39a9-af3e-1aae4363ca2d.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值