Spring——Spring的事务控制(2)升级篇

2024-01-08 21:35:33

1.改造转账案例

1.1.applicationContext.xml

 	<!--配置事物管理器-->
    <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--配置事物属性-->
    <bean class="org.springframework.transaction.support.DefaultTransactionDefinition">
        <property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
        <property name="readOnly" value="false"></property>
    </bean>

1.2.service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TransactionDefinition txDefinition;
    @Autowired
    private PlatformTransactionManager txManager;
    /**
     * 转账
     * @param source
     * @param target
     * @param money
     */
    @Override
    public void updateUser(String source, String target, Float money) {
        // 获取一个事务
        TransactionStatus txStatus = txManager.getTransaction(txDefinition);
        try {

            userMapper.updateUserOfSub(source, money);
            int a = 6/0;
            userMapper.updateUserOfAdd(target, money);
            //提交事务
            txManager.commit(txStatus);
        }catch (Exception e){
            //回滚事务
            txManager.rollback(txStatus);
            e.printStackTrace();
        }
    }
}

1.3.测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件
public class ServiceTest {
    @Autowired
    private UserService userService;
    /**
     * 转账业务
     */
    @Test
    public void testUpdate(){
        userService.updateUser("张三丰","宋远桥",1F);
    }
}
  • 事务回滚:

    在这里插入图片描述

  • 满足执行:

    在这里插入图片描述

  • 我们现在虽然实现了事务控制,但是代码非常的臃肿,我们可以使用动态代理简化代码

2.动态代理控制事务

2.1.factory

我们创建一个工厂,专门用来给 Service 创建代理对象,如下:

package com.wt.factory;

import com.wt.service.UserService;
import com.wt.service.UserServiceImpl;
import org.hamcrest.Factory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * bean工厂
 */
@Component
public class BeanFactory {
    @Autowired
    private UserService userService;
    @Autowired
    private TransactionDefinition txDefinition;
    @Autowired
    private PlatformTransactionManager txManager;

    /**
     * 获得UserServiceImpl对象
     *
     * @return
     */
    public UserService getUserService() {
        return (UserService) Proxy.newProxyInstance(
            userService.getClass().getClassLoader(),
            userService.getClass().getInterfaces(),
            new InvocationHandler() {
                    public Object invoke(Object proxy, Method method, Object[] args)
                        											throws Throwable {
                        //开启事务
                        TransactionStatus txStatus = 
                            txManager.getTransaction(txDefinition);
                        try {
                            method.invoke(userService, args);
                            //提交事务
                            txManager.commit(txStatus);
                        } catch (Exception e) {
                            //回滚事务
                            txManager.rollback(txStatus);
                            e.printStackTrace();
                        }
                        return null;
                    }
                });
    }
}

2.2.applicationContext.xml

<!--配置service代理对象-->
<bean id="proxyService" factory-bean="beanFactory" factory-method="getUserService"></bean>

2.3.service

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 转账
     * @param source
     * @param target
     * @param money
     */
    @Override
    public void updateUser(String source, String target, Float money) {
        userMapper.updateUserOfSub(source, money);
        int a = 6/0;
        userMapper.updateUserOfAdd(target, money);
    }
}

2.4.测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class ServiceTest {
    @Autowired
    @Qualifier("proxyService")//注入代理对象
    private UserService userService;

    @Test
    public void testUpdate(){
        userService.updateUser("张三丰","宋远桥",1F);
    }
}
  • 事务回滚:

在这里插入图片描述

3.Spring AOP控制事务

3.1.导入schema约束

<?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:tx="http://www.springframework.org/schema/tx" 
       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/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <!--配置事物属性
    <bean class="org.springframework.transaction.support.DefaultTransactionDefinition">
        <property name="propagationBehaviorName" value="PROPAGATION_REQUIRED"/>
        <property name="readOnly" value="false"></property>
    </bean>

    配置service代理对象
    <bean id="proxyService" factory-bean="beanFactory" factory-method="getUserService"> 
    </bean>-->
</beans>    

3.2.配置增强

    <!-- 1、增强 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!--事务属性-->
        <tx:attributes>
        <!-- 指定方法名称:是业务核心方法
            read-only:是否是只读事务。默认false,不只读。
            isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。
            propagation:指定事务的传播行为。
            timeout:指定超时时间。默认值为:-1。永不超时。
            rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。
						 省略时任何异常都回滚。
            -->
        <tx:method name="*" read-only="false" propagation="REQUIRED"/>
        <tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
        <tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
       </tx:attributes>
    </tx:advice>

3.3.配置切点

    <aop:config>
        <!--2、切点-->
        <aop:pointcut expression="execution(* com.wt.service.*.*(..))" id="pointcut"/>
    </aop:config>

3.4.配置切面

    <aop:config>
        <!--3、切面-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>

3.5.factory

删除bean工程

3.6.测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件
public class ServiceTest {
    @Autowired
    private UserService userService;
    /**
     * 转账业务
     */
    @Test
    public void testUpdate(){
        userService.updateUser("张三丰","宋远桥",1F);
    }
}
  • 事务回滚:

    在这里插入图片描述

  • 问题一:如果我们把方法名称改了,那么事务还会回滚吗?

    • 修改applicationContext.xml:

    • 修改service:

  • 问题二:如果我们把异常捕捉了,那么事务还会回滚吗?

文章来源:https://blog.csdn.net/wan_m_m/article/details/135466361
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。