Spring 事务管理-只记录xml部分

1.手动配置事务的方式是

applicationContext.xml

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

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>

        </bean>

         <bean id="accountDao" class="com.test.spring.aop.tansation.example.dao.AccountDaoImpl">
             <property name="dataSource" ref="dataSource"></property>
         </bean>

         <bean id="accountService" class="com.test.spring.aop.tansation.example.service.AccountServiceImpl">
             <property name="accountDao" ref="accountDao"></property>
             <property name="transactionTemplate" ref="transationTemplate"></property>
         </bean>

         <!-- 手动方式 -->
         <bean id="transationTemplate" class="org.springframework.transaction.support.TransactionTemplate">
             <property name="transactionManager" ref="txManage"></property>
         </bean>

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

dao层(接口类这里不写)

package com.test.spring.aop.tansation.example.dao;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

public class AccountDaoImpl extends JdbcDaoSupport implements AccountDao {

    public void in(String inner, int money) {
        this.getJdbcTemplate().update("update account set money = money -? where username = ?", money, inner);

    }

    public void out(String outter, int money) {
        this.getJdbcTemplate().update("update account set money = money +? where username = ?", money, outter);
    }

}

service层

package com.test.spring.aop.tansation.example.service;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.test.spring.aop.tansation.example.dao.AccountDao;

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public void tansfer(final String inner, final String outter, final int money) {

        //手动方式配置
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {

            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                accountDao.out(outter, money);          //遇到异常时,事务回滚
                int i = 1/0;
                accountDao.in(inner, money);

            }
        });

    }

}

测试

package com.test.spring.aop.tansation.example;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.test.spring.aop.tansation.example.service.AccountService;

public class TestExample {

    @Test
    public void test() {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("com/test/spring/aop/tansation/example/applicationContext.xml");

        AccountService as = ctx.getBean("accountService",AccountService.class);

        as.tansfer("jack", "peter", 200);
    }
}

2.半自动,使用代理的方式

这里只需要修改一下service层和配置就可以了

applicationContext.xml

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

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>

        </bean>

         <bean id="accountDao" class="com.test.spring.aop.tansation.example.dao.AccountDaoImpl">
             <property name="dataSource" ref="dataSource"></property>
         </bean>

         <bean id="accountService" class="com.test.spring.aop.tansation.example.service.AccountServiceImpl">
             <property name="accountDao" ref="accountDao"></property>
             <property name="transactionTemplate" ref="transationTemplateProxy"></property>
         </bean>

         <!-- 半自动方式 -->
         <!-- 事务代理工厂类
                 参数1:接口
                 参数2:实现类
                 参数3:事务管理器
                 参数4:事务属性(事务详情)
                     prop.key:确认那些方法使用事务
                     prop.value:事务详情 具体参数信息可以查阅TransactionDefinition类
                         格式:Propagation,Isolation,readOnly,-Exception,+Exception
                         Propagation:传播行为
                         Isolation:隔离级别
                         readOnly:连接是否只读
                         -Exception:当遇到异常时,回滚
                         +Exception:当遇到异常时,提交
                 例子1:默认传播行为和隔离级别
                     <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT</prop>
                 例子2:只读,连接只读,不能进行update操作
                     <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly</prop>
                 例子3:当遇到指定异常时,提交仍然提交事务,以为着之前执行的都将提交
                     <prop key="transfer">PROPAGATION_REQUIRED,ISOLATION_DEFAULT,+java.lang.ArithmeticException</prop>
          -->
         <bean id="transationTemplateProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
             <property name="proxyInterfaces" value="com.test.spring.aop.tansation.example.service.AccountService"></property>
             <property name="target" ref="accountService"></property>
             <property name="transactionManager" ref="txManage"></property>
             <property name="transactionAttributes">
                 <props>
                     <prop key="transfer"></prop>
                 </props>
             </property>
         </bean>

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

         </bean>
</beans>

service层

package com.test.spring.aop.tansation.example.service;

import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.test.spring.aop.tansation.example.dao.AccountDao;

public class AccountServiceImpl implements AccountService {

    private AccountDao accountDao;
    private TransactionTemplate transactionTemplate;

    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
        this.transactionTemplate = transactionTemplate;
    }

    public void tansfer(final String inner, final String outter, final int money) {

        accountDao.out(outter, money);
        int i = 1/0;
        accountDao.in(inner, money);

    }

}

3. 使用spring自动的方式

根据上面的一大串配置,会是很头疼,现在就是用全自动,简化上面繁琐的配置,除了修改配置外,其余的都不需要修改

<?xml version="1.0" encoding="UTF-8" ?>
<beans   xmlns="http://www.springframework.org/schema/beans"
         xmlns:context="http://www.springframework.org/schema/context"
         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"
         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/aop
                              http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
                              http://www.springframework.org/schema/tx
                              http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>

        </bean>

         <bean id="accountDao" class="com.test.spring.aop.tansation.example.dao.AccountDaoImpl">
             <property name="dataSource" ref="dataSource"></property>
         </bean>

         <bean id="accountService" class="com.test.spring.aop.tansation.example.service.AccountServiceImpl">
             <property name="accountDao" ref="accountDao"></property>
             <!-- <property name="transactionTemplate" ref="transationTemplate"></property> -->
             <property name="transactionTemplate" ref="transationTemplateProxy"></property>
         </bean>

         <!-- 全自动
             这里分为3块,具体的流程是,先有一个事务管理器,然后有一个事务管理通知,最后一个aop的切面配置,
             对切面配置中的切入点进行事务管理,当遇到与事务管理通知配置中相符合的类名时,进行与之相符的配置行为,例如只读,或者异常提交等
          -->
         <!-- 1.事务管理器 -->
         <bean id="txManage" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
             <property name="dataSource" ref="dataSource"></property>
         </bean>
         <!-- 2.事务通知
             tx:method 就是指定那个方法,需要使用事务,而事务的详情就由里面的几个属性类决定
         -->
         <tx:advice id="txAdvice" transaction-manager="txManage">
             <tx:attributes>
                 <tx:method name="transfer" propagation="REQUIRED" isolation="DEFAULT"/>
             </tx:attributes>
         </tx:advice>
         <!-- 3.aop切面类 -->
         <aop:config>
             <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.test.spring.aop.tansation.example.service.AccountServiceImpl.*(..))"/>
         </aop:config>

</beans>

原文地址:https://www.cnblogs.com/oscar1987121/p/10960570.html

时间: 2024-08-01 05:54:26

Spring 事务管理-只记录xml部分的相关文章

Spring事务管理只对出现运行期异常进行回滚

使用spring难免要用到spring的事务管理,要用事务管理又会很自然的选择声明式的事务管理,在spring的文档中说道,spring声明式事务管理默认对非检查型异常和运行时异常进行事务回滚,而对检查型异常则不进行回滚操作.那么什么是检查型异常什么又是非检查型异常呢?最简单的判断点有两个:1.继承自runtimeexception或error的是非检查型异常,而继承自exception的则是检查型异常(当然,runtimeexception本身也是exception的子类). 2.对非检查型类

Spring事务管理(详解+实例)

写这篇博客之前我首先读了<Spring in action>,之后在网上看了一些关于Spring事务管理的文章,感觉都没有讲全,这里就将书上的和网上关于事务的知识总结一下,参考的文章如下: Spring事务机制详解 Spring事务配置的五种方式 Spring中的事务管理实例详解 1 初步理解 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必须是要么都执行要么都

Spring事务管理

写这篇博客之前我首先读了<spring in action>,之后在网上看了一些关于Spring事务管理的文章,感觉都没有讲全,这里就将书上的和网上关于事务的知识总结一下,参考的文章如下: Spring事务机制详解 Spring事务配置的五种方式 Spring中的事务管理实例详解 1 初步理解 理解事务之前,先讲一个你日常生活中最常干的事:取钱. 比如你去ATM机取1000块钱,大体有两个步骤:首先输入密码金额,银行卡扣掉1000元钱:然后ATM出1000元钱.这两个步骤必须是要么都执行要么都

Spring 事务管理高级应用难点剖析--转

第 1 部分 http://www.ibm.com/search/csass/search/?q=%E4%BA%8B%E5%8A%A1&sn=dw&lang=zh&cc=CN&en=utf&hpp=20&dws=cndw&lo=zh 概述 Spring 最成功,最吸引人的地方莫过于轻量级的声明式事务管理,仅此一点,它就宣告了重量级 EJB 容器的覆灭.Spring 声明式事务管理将开发者从繁复的事务管理代码中解脱出来,专注于业务逻辑的开发上,这是一件

Spring事务管理----------整合学习版

作者:学无先后 达者为先 Spring提供了一流的事务管理.在Spring中可以支持声明式事务和编程式事务. 一  spring简介 1 Spring的事务       事务管理在应用程序中起着至关重要的作用:它是一系列任务的组成工作单元,在这个工作单元中,所有的任务必须同时执行.它们只有二种可能执行结果,要么所有任务全部执行成功,要么所有任务全部执行失败.     Spring中提供了丰富的事务管理功能,它们超过了EJB并且和EJB一样支持声明式事务,重要的是Spring提供了一致的事务管理,

spring事务管理——编程式事务、声明式事务

本教程将深入讲解 Spring 简单而强大的事务管理功能,包括编程式事务和声明式事务.通过对本教程的学习,您将能够理解 Spring 事务管理的本质,并灵活运用之. 先决条件 本教程假定您已经掌握了 Java 基础知识,并对 Spring 有一定了解.您还需要具备基本的事务管理的知识,比如:事务的定义,隔离级别的概念,等等.本文将直接使用这些概念而不做详细解释.另外,您最好掌握数据库的基础知识,虽然这不是必须. 系统需求 要试验这份教程中的工具和示例,硬件配置需求为:至少带有 512MB 内存(

[Spring框架]Spring 事务管理基础入门总结.

前言:在之前的博客中已经说过了数据库的事务, 不过那里面更多的是说明事务的一些锁机制, 今天来说一下Spring管理事务的一些基础知识. 之前的文章: [数据库事务与锁]详解一: 彻底理解数据库事务一, 什么是事务 事务是逻辑上一组操作,这组操作要么全都成功,要么全都失败. 事务的属性: ACID原子性(Atomicity): 事务作为一个整体被执行,包含在其中的对数据的操作要么全部被执行,要么都不执行.一致性(Consistency):事务应确保数据库的状态从一个一致状态转变为另一个一致状态.

Spring第三天——JdbcTemplate和spring事务管理

大致内容: aspectJ的aop操作(基于注解,对比day02配置操作)(会用) *jdbcTemplate操作(实现CRUD) *spring配置连接池 *spring事务管理 一.AspectJ的基于注解的AOP操作 (day02的配置回顾,略显麻烦,配置稍多) 建立项目记得导入day02操作aop的那些包(如果是复制项目一定要修改项目的context name) 再把配置文件拿过来 <?xml version="1.0" encoding="UTF-8"

【转】Spring事务管理

原文链接 在 Spring 中,事务是通过 TransactionDefinition 接口来定义的.该接口包含与事务属性有关的方法.具体如清单 1 所示: 清单 1. TransactionDefinition 接口中定义的主要方法 public interface TransactionDefinition{ int getIsolationLevel();//isolation 隔离 int getPropagationBehavior();//Propagation 传播 int get