spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- 1.開啟 注解 -->
<context:component-scan base-package="com.test" />
<!-- 2.創(chuàng)建數(shù)據(jù)源對象-->
<context:property-placeholder location="db.properties" />
<bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${url}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
</bean>
<!-- 3.創(chuàng)建JdbcTemplate對象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg name="dataSource" ref="comboPooledDataSource" />
</bean>
<!-- 4 創(chuàng)建一個事務(wù)管理器 -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="comboPooledDataSource" />
</bean>
<!-- 5.開啟事務(wù)注解-->
<tx:annotation-driven transaction-manager="txManager" />
</beans>
方法
package com.test.service.impl;
import com.test.dao.ICardInfoDao;
import com.test.exception.MyException;
import com.test.service.ICardInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CardInfoService implements ICardInfoService {
@Autowired
private ICardInfoDao cardInfoDao;
public ICardInfoDao getCardInfoDao() {
return cardInfoDao;
}
public void setCardInfoDao(ICardInfoDao cardInfoDao) {
this.cardInfoDao = cardInfoDao;
}
//實現(xiàn)轉(zhuǎn)賬方法
@Override
//通過注解的方式 聲明事務(wù)方法 (隔離級別 傳播行為 回滾的條件)
@Transactional(isolation = Isolation.DEFAULT,propagation = Propagation.REQUIRED,rollbackFor =MyException.class )
public void transfer(int from, int to, float money) throws Exception {
//一方減錢
cardInfoDao.decreaseMoney(from,money);
if(true)
throw new MyException("轉(zhuǎn)賬異常");
//一方加錢
cardInfoDao.increaseMoney(to,money);
}
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-699140.html
文章來源:http://www.zghlxwxcb.cn/news/detail-699140.html
到了這里,關(guān)于javaee spring 聲明式事務(wù)管理方式2 注解方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!