Spring事务管理分成了两类:编程式事务管理和声明式事务管理
一、编程式的事务管理
配置:
<bean id="xxxService" class="com.genius.service.impl.xxxService">
<property name="xxxDao" ref="xxxDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
调用:
public class XxxService {
private XxxDao xxxDao;
private TransactionTemplate transactionTemplate;
public void transfer(){
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
}
})
}
}
二、声明式的事务管理
- 基于TransactionProxyFactoryBean的方式(很少使用)
注:需要为每个进行事务管理的类,配置一个TransactionProxyFactoryBean进行增强
配置:
<bean id="xxxService" class="com.genius.service.impl.xxxService">
<property name="xxxDao" ref="xxxDao"></property>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="xxxServiceProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager" ref="transactionManager"></property>
<property name="target" ref="xxxService"></property>
<property name="transactionAttributes">
<props>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
调用:
要注入代理类xxxServiceProxy而不能注入原有的类xxxService,否则事务不起作用
- 基于AspectJ的XML方式(经常使用)
注:一旦配置好之后,类上不需要添加任何东西(非常清楚的可以看出哪些类使用了事务)
配置:
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.sinosoft.rpf.service..*Impl.*(..))" />
<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
</aop:config>
调用:直接写业务类,不需要任何其它操作
- 基于注解的方式(经常使用)
注:配置很简单,使用方便,只需在业务层类上添加一个@Transaction的注解
配置:
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
调用:
业务类上添加@Transaction的注解即可完成事务管理