Spring AOP 控制事物

一、案例分析

    转账案例: A给B转账 A的钱减少,B的钱增加,A的钱减少正常运行时,中间运行个÷0的异常,然后再写B的钱增加的业务。

二、源代码

      ( 1 )  log4j.properties

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

  (2)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: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">
    <!--ioc-->
    <context:component-scan base-package="com.by.service,com.by.factory"></context:component-scan>

    <!--加载db.properties-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!--数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--sqlSessionFactory-->
    <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--告诉mybatis扫描mapper接口生成代理类,并交给spring的ioc容器去管理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.by.mapper"></property>
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
    </bean>

    <!--DataSourceTransactionManager:是一个事务管理器,负责开启、提交或回滚事务-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!--DefaultTransactionDefinition:定义事务的属性-->
    <!--
    <bean id="transactionDefinition" class="org.springframework.transaction.support.DefaultTransactionDefinition">

            隔离级别:默认值DEFAULT,等价于REPEATABLE_READ
            传播行为:默认值REQUIRED,methodB()会加入到methodA()事务中
            事务超时:默认值-1,永不超时
            是否只读:默认值false,适用于增删改
            回滚规则:可省略
    </bean>
     -->

    <!--配置userService的代理对象,并交给spring容器去管理-->
    <!-- <bean id="proxyUserService" factory-bean="beanFactory" factory-method="getProxyBean"></bean>-->

    <!--增强(advice):要搞的事情,eg:日志、事务-->
    <tx:advice id="txManager" transaction-manager="transactionManager">
        <!--定义事务的属性:
                隔离级别:默认值DEFAULT,使用mysql的默认隔离级别即REPEATABLE_READ
                传播行为:默认值REQUIRED,有则加入没有则新建
                事务超时:默认值-1,永不超时
                是否只读:默认值false,false加log 适合增删改;true不加日志 适合查询;
                回滚规则:可省略,所有运行时异常都回滚
        -->
        <tx:attributes>
            <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
            <tx:method name="*"></tx:method>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <!--切点(pointcut):要增强的方法-->
        <aop:pointcut id="pointcut" expression="execution(* com.by.service.*.*(..))"/>
        <!--切面(aspect):把增强应用到切点上-->
        <aop:advisor advice-ref="txManager" pointcut-ref="pointcut"></aop:advisor>
    </aop:config>
</beans>

(3)db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3305/spring?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=

  (4) pom.xml

  <properties>
        <!-- 项目源码及编译输出的编码 -->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <!-- 项目编译JDK版本 -->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- Spring常用依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <!-- MySql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--连接池-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>
        <!--日志-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

  (5)持久层

①mapper

package com.by.mapper;

import com.by.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

public interface UserMapper {


    void updateUser1(@Param("source") String source, @Param("money") float money);

    void updateUser2(@Param("target") String target, @Param("money") float money);
}

 ②映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.by.mapper.UserMapper">

    <!--转账-->
    <update id="updateUser1">
        update t_user set money=money-#{money} where name=#{source}
    </update>

    <update id="updateUser2">
        update t_user set money=money+#{money} where name=#{target}
    </update>
</mapper>

(6)业务层

package com.by.service;

import com.by.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public void updateUser1(String source, String target, float money) {

        //扣钱
        userMapper.updateUser1(source, money);
        int a = 6 / 0;
        //加钱
        userMapper.updateUser2(target, money);

    }

}

 (7)pojo


package com.by.pojo;

import org.springframework.stereotype.Component;
public class User {
    private Integer id;
    private String name;
    private Float money;

    public User(String name, Float money) {
        this.name = name;
        this.money = money;
    }

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName(String 张三) {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney(float v) {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }
}

(8)表现层

/*
 * Copyright (c) 2020, 2024, webrx.cn All rights reserved.
 *
 */
package com.by.servlet;

import com.by.pojo.User;
import com.by.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")//加载配置文件
public class Client {
//   注入servoce
    @Autowired
    private UserService userService;
    @Test
//    转账业务
    public void updateUser(){
        userService.updateUser1("杨逍","范瑶",1F);

    }

}

 

三、运行结果

发现异常时 进行回滚

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今天的接口写完了吗?

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值