spring宣言式事务管理中常用的3种
spring声明式事务管理中常用的3种
spring的事务管理有声明式和编程式两种,声明式事务依赖spring的AOP框架完成,它不会侵入到开发组件的内部.
事务配置好后,所有被事务管理的方法中一旦发生异常(当然我们可以设定某些异常不回滚等),所有需要提交到数据库的操作都会回滚.
下面总结声明式事务中的三种:
一.使用代理的方式
1.配置事务管理类:
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean>
2.配置代理对象bean
<bean id="bmhServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager" /> </property> <property name="proxyInterfaces"> <list> <value>com.bmh.service.IBmhService</value> </list> </property> <property name="target"> <ref bean="bmhService" /> </property> <property name="transactionAttributes"> <props> <prop key="test*">PROPAGATION_REQUIRED,+TestException</prop> </props> </property> </bean>
1).proxyInterfaces是要代理的对象的借口
2).target是要代理的对象,这里代理了名为bmhService的bean
3).test*指定了以test开头的方法都纳入事务管理,事务管理会自动介入到方法的前后
4).+TestException表示发生该异常时立即提交,如果是"-"表示发生该异常时撤销操作
3.需要注意的是,如下配置将达不到配置事务的作用
<bean id="bmhAction" class="com.bmh.action.BmhAction">
<property name="bs" ref="bmhService
"></property>
</bean>
<bean id="bmhService" class="com.bmh.service.impl.BmhService">
<property name="bd" ref="bmhDao"></property>
</bean>
这里bmhAction中属性的引用有错,需要引用代理了bmhService的bmhServiceProxy才用事务管理的功能,不然配置了那么多,结果没引用到,那当然也没作用
二.使用切面方式
1.配置事务管理类:同上
2.使用<aop>进行拦截:
<aop:config> <aop:pointcut id="transactionPointcut" expression="execution(* com.bmh.service..*.*(..))" /> <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut" /> </aop:config>
a)spring容器会自动给拦截到的类生成代理对象,
b)拦截到service包及所有子包下所有类的所有方法,给这些方法引用一个事务通知
3.使用<tx>标签提供事务advice
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED" /> <tx:method name="test*" /> </tx:attributes> </tx:advice>
对get开头的方法不使用事务,而对test开头的方法使用默认的事务操作,比如传播属性是REQUIRED
三.使用注解的方式
1.配置事务管理类,同上
2.声明使用注解配置事务
<tx:annotation-driven transaction-manager="transactionManager"/>
3.在需要事务管理的类上加注解
@Service("bmhService") @Transactional public class BmhService implements IBmhService {
也可以加在具体方法上
@Transactional(propagation=Propagation.REQUIRED) public void testTx(){ bd.testTx1(); bd.testTx2(); }