AOP的配置稍显复杂,通过[color=red]@Transactional[/color]注解,同样可以实现:
1. 在需要事务的类或方法上加[color=red]@Transactional[/color]:
如果是类上加注解,该类的所有public方法都会应用事务
如果是方法上加注解,该方法会应用事务。
在接口上加注解有风险,如果使用CGLIB(类代理)将不会启用事务。
2. 开启注解事务开关:[color=red]<tx:annotation-driven />[/color]
FruitShop实现:
beans-fruitshop-@.xml文件:
测试类和之前的类似:
附:
Spring底层也是通过AOP来实现对@Transactional注解事务的支持:
[img]http://dl2.iteye.com/upload/attachment/0099/7732/87027e38-ba94-39a9-af3e-1aae4363ca2d.png[/img]
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]