Spring的事务管理(注解)

注解与XML配置的主要差别在配置文件和service中。所以这里只上主要代码,其他参考这里  

service

package com.kye.serviceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kye.dao.AccountDao;
import com.kye.service.AccountService;

@Service("service")
public class AccountServiceImpl implements AccountService {

	@Autowired
	@Qualifier("accountDao")
	AccountDao dao;

	public void setDao(AccountDao dao) {
		this.dao = dao;
	}

	@Transactional
	@Override
	public void transfer(int monehy) {
		dao.add(monehy);
		 int a = 1 / 0;
		dao.add(monehy);
	}

	@Override
	public int get() {
		return dao.get();
	}

}

配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" 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/aop 
       					   http://www.springframework.org/schema/aop/spring-aop.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">

    <!-- <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl"
                value="jdbc:mysql://127.0.0.1/db"></property>
            <property name="user" value="root"></property>
            <property name="password" value="1234"></property>
        </bean> -->
	<bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"></property>
		<property name="jdbcUrl"
			value="jdbc:sqlserver://127.0.0.1:1433;DatabaseName=erp"></property>
		<property name="user" value="sa"></property>
		<property name="password" value="sa123456"></property>
	</bean>

	<bean id="accountDao" class="com.kye.daoImpl.AccountDaoImpl">
		<property name="dataSource" ref="c3p0"></property>
	</bean>

	<bean id="service" class="com.kye.serviceImpl.AccountServiceImpl">
		<property name="dao" ref="accountDao"></property>
	</bean>

	<bean id="txManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="c3p0"></property>
	</bean>

	<tx:annotation-driven transaction-manager="txManager" />
</beans>


原文地址:https://www.cnblogs.com/wugang/p/14232335.html