Spring Transaction 五: 使用基于注解的AOP的事务管理
xml aop事务管理
1. Example
<tx:annotation-driven transaction-manager="txManager"/> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="get*" read-only="false"/><tx:method name="*"/></tx:attributes> </tx:advice> <aop:config><aop:pointcut id="pointcut" expression="execution(* com.mycompany.service.*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/> </aop:config>
2. tx:advice 标签
tx:advice 必须设置 transaction-manager , 它必须引用一个PlatformTransactionManager 的bean
出此外, 还可以更详细的设置
<tx:advice id="txAdvice" transaction-manager="txManager"><tx:attributes><tx:method name="*" isolation="READ_COMMITED" propagation="REQUIRED" timeout="100"/> <tx:method name="get*" readonly=true/></tx:attributes> </tx:advice>
3. tx:method 的属性
name
方法名的匹配模式,通知根据该模式寻找匹配的方法。
该属性可以使用asterisk (*)通配符
propagation
设定事务定义所用的传播级别
isolation
设定事务的隔离级别
timeout
指定事务的超时(单位为秒)
read-only
该属性为true指示事务是只读的(典型地,对于只执行查询的事务你会将该属性设为true,如果出现了更新、插入或是删除语句时只读事务就会失败)
no-rollback-for
以逗号分隔的异常类的列表,目标方法可以抛出这些异常而不会导致通知执行回滚
rollback-for
以逗号分隔的异常类的列表,当目标方法抛出这些异常时会导致通知执行回滚。默认情况下,该列表为空,
因此不在no-rollback-for列表中的任何运行时异常都会导致回滚