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

AOP的配置稍显复杂,通过 @Transactional注解,同样可以实现:

1. 在需要事务的类或方法上加 @Transactional

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

2. 开启注解事务开关: <tx:annotation-driven />

FruitShop实现:
public class AnnotationTxFruitShop extends JdbcDaoSupport implements FruitShop {

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


[email protected]文件:
  <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:/[email protected]" })
public class AnnotationTxFruitShopTest {

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

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



附:
Spring底层也是通过AOP来实现对@Transactional注解事务的支持:

猜你喜欢

转载自czj4451.iteye.com/blog/2099673