Spring事务的实现方式
1、编程式事务
通过代码的方式来实现:
先进行配置环境,再用代码实现
<!--开启注解(扫包)-->
<context:component-scan base-package="com.mgg.spring" />
<context:property-placeholder location="jdbc.properties" />
<!--事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private PlatformTransactionManager transactionManager;
@Override
public void transfer(String fromAccount, String toAccount, BigDecimal money) {
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus transaction = transactionManager.getTransaction(definition);
String fromSql = "update account set balance = balance - ? where account_no = ?";
String toSql = "update account set balance = balance + ? where account_no = ?";
try {
jdbcTemplate.update(fromSql, money, fromAccount);
int a = 1/0;
jdbcTemplate.update(toSql, money, toAccount);
} catch (RuntimeException ex){
ex.printStackTrace();
//回滚事务
transactionManager.rollback(transaction);
}
transactionManager.commit(transaction);
}
通过AOP方式实现:
使用方法拦截器,当方法执行有异常时回滚事务,否则提交事务
环境配置加入以下配置,再使用方法拦截器实现
<!--配置JdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
<!--自定义事务通知-->
<bean id="txAdvice" class="com.mgg.spring.aop.TxAdvice">
<property name="transactionManager" ref="txManager" />
</bean>
<aop:config>
<aop:pointcut id="methodPoint" expression="execution(* com.mgg.spring.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="methodPoint" />
</aop:config>
PlatformTransactionManager transactionManager;
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
System.out.println("拦截方法>>>>");
DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
TransactionStatus transaction = transactionManager.getTransaction(definition);
Object returnObj = null;
try {
returnObj = invocation.getMethod().invoke(
invocation.getThis(),
invocation.getArguments()
);
} catch (RuntimeException ex){
ex.printStackTrace();
transactionManager.rollback(transaction);
}
transactionManager.commit(transaction);
return returnObj;
}