7、SpringBoot2之整合事务及AOP

本文在SpringBoot2之整合Mybatis的基础上进行

7.1、整合事务

7.1.1、mapper接口

image

    int deleteEmployeeById(int id);

7.1.2、mapper映射文件

image

    <delete id="deleteEmployeeById" parameterType="int">
        delete from t_emp where emp_id = #{id}
    </delete>

7.1.3、业务层接口及实现类

image

package online.liaojy.service;

/**
 * @author liaojy
 * @date 2023/12/25 - 6:31
 */
public interface EmployeeService {

    int deleteEmployeeById(int id);

}

image

注意:只要引入 spring-boot-starter-jdbc 启动器(详见6.1节),spring boot 便会自动配置好 DataSourceTransactionManager ;
因此,只需在方法(或者类)加上 @Transactional 注解,即可进行事务管理。

package online.liaojy.service.impl;

import online.liaojy.mapper.EmployeeMapper;
import online.liaojy.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author liaojy
 * @date 2023/12/25 - 6:33
 */
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Transactional
    @Override
    public int deleteEmployeeById(int id) {

        // 删除一条数据
        int rowsOfDelete = employeeMapper.deleteEmployeeById(id);
        System.out.println("已成功删除"+rowsOfDelete+"行数据");

        // 制造一个异常
        int i = 1/0;

        return rowsOfDelete;
    }

}

7.1.4、控制层方法

image

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/deleteEmployeeById")
    public String deleteEmployeeById(){
        int i = employeeService.deleteEmployeeById(26);
        return "删除成功";
    }

7.1.5、测试效果

image

测试前的数据

image

测试时发生异常

image

测试后的数据没变化,说明事务回滚功能正常

7.2、整合AOP

7.2.1、导入AOP启动器依赖

image

        <!-- AOP启动器的依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

7.2.2、创建切面类

image

package online.liaojy.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author liaojy
 * @date 2023/12/25 - 6:51
 */
@Component
@Aspect
@Order(5)
public class LogAdvice {

    @Before("execution(* online.liaojy.service.*.*.*(..))")
    public void beforeLog(JoinPoint joinPoint){
        // 获取连接点所对应目标方法所在类的名称
        String className = joinPoint.getSignature().getClass().getSimpleName();
        // 获取连接点所对应目标方法的名称
        String methodName = joinPoint.getSignature().getName();

        System.out.println(className+"类的"+methodName+"方法开始执行了!");
    }

}

7.2.3、测试效果

image

posted @ 2024-01-06 17:32  Javaer1995  阅读(123)  评论(0编辑  收藏  举报