<?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:aop="http://www.springframework.org/schema/aop"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- bean definitions here --><!-- 1.引入配置文件 --><context:property-placeholder location="classpath:jdbc.properties"/><!-- 2.配置C3P0连接池 --><bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driverClass}"></property><property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property><property name="user" value="${jdbc.user}"></property><property name="password" value="${jdbc.password}"></property></bean><!-- 3.配置事务管理器 (吧连接池放入事务管理器中)--><bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="comboPooledDataSource"></property></bean><!-- 4.开启注解事务 --><tx:annotation-driven transaction-manager="dataSourceTransactionManager"/><!-- 5.配置DAO层实例化对象,并且传入连接池供父类引用 --><bean id="accountDao" class="com.mickeymouse.dao.impl.AccountDaoImpl"><property name="dataSource" ref="comboPooledDataSource"></property></bean><!-- 6.配置service层 --><bean id="accountService" class="com.mickeymouse.service.impl.AccountServiceImpl"><!-- 属性注入 --><property name="dao" ref="accountDao"></property></bean></beans>
package com.mickeymouse.service.impl;import org.springframework.transaction.TransactionStatus;import org.springframework.transaction.annotation.Transactional;import org.springframework.transaction.support.TransactionCallback;import org.springframework.transaction.support.TransactionCallbackWithoutResult;import org.springframework.transaction.support.TransactionTemplate;import com.mickeymouse.dao.AccountDao;import com.mickeymouse.service.AccountService;@SuppressWarnings("all")public class AccountServiceImpl implements AccountService{private AccountDao dao;public void setDao(AccountDao dao) {this.dao = dao;}/*** 转账汇款*/@Transactionalpublic void transfer(final String deletename, final String addname, final int money) {dao.addmoney(addname, money);//int i = 1/0;//模拟断电dao.deletemoney(deletename, money);}}
原文:http://my.oschina.net/mickeymouse/blog/516823