Spring-AOP面相切面编程示例(有详细注释)

前提知识Spring-IOC容器注解方式使用icon-default.png?t=N7T8https://blog.csdn.net/m0_61160520/article/details/136784799?spm=1001.2014.3001.5501
切点表达式icon-default.png?t=N7T8https://blog.csdn.net/m0_61160520/article/details/136782885?spm=1001.2014.3001.5501

案例 

1.创建项目

2.导入依赖

    <dependencies>
        <!--spring context依赖-->
        <!--当你引入Spring Context依赖之后,表示将Spring的基础依赖引入了-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!--junit5测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.3.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!-- spring整合aspectj框架的依赖 , 传到aspect框架依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>6.0.6</version>
        </dependency>
    </dependencies>

 3.准备并实现接口

package com.example.service;
public interface Calculator {
    int add(int i, int j);
    int sub(int i, int j);
    int mul(int i, int j);
    int div(int i, int j);
}
package com.example.service.impl;
import org.springframework.stereotype.Component;
@Component
public class CalculatorPureImpl  {
    public int add(int i, int j) {
        return i + j;
    }   

    public int sub(int i, int j) {
        return i - j;
    }
    
    public int mul(int i, int j) {
        return i * j;
    }
    
    public int div(int i, int j) {
        return i / j;
    }
}

4.实现配置类

package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy //开启aspectj的注解 <aop:aspectj-autoproxy />
public class JavaConfig {
}

5.配置切点

package com.example.pointcut;

import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Component
public class MyPointCut {
    //impl.*.*(..)意思是包下的某个类的某个方法
    @Pointcut("execution(* com.example.service.impl.*.*(..))")
    public void pc(){}

    @Pointcut("execution(* com..impl.*.*(..))")
    public void myPc(){}

}

6.定义增强类

package com.example.advice;

import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * description: 增强类的内部要存储增强代码
 *
 *   1. 定义方法存储增强代码
 *      具体定义几个方法,根据插入的位置决定!
 *   2. 使用注解配置 指定插入目标方法的位置
 *       前置   @Before
 *       后置   @AfterReturning
 *       异常   @AfterThrowing
 *       最后   @After
 *       环绕   @Around
 *
 *       try{
 *           前置
 *           目标方法执行
 *           后置
 *       }catch(){
 *           异常
 *       }finally{
 *           最后
 *       }
 *
 *   3. 配置切点表达式 [选中插入的方法   切点]
 *
 *   4.补全注解
 *      加入ioc容器 @Component
 *      配置切面  @Aspect  =  切点 + 增强
 *
 *   5.开启aspect注解的支持
 */
@Component
@Aspect
@Order(20)//多个增强类时,数字越小越先执行
public class LogAdvice {

    @Before("com.example.pointcut.MyPointCut.pc()")
    public void start(){
        System.out.println("方法开始了");
    }

    @After("com.example.pointcut.MyPointCut.pc()")
    public void after(){
        System.out.println("方法结束了");
    }

    @AfterThrowing("com.example.pointcut.MyPointCut.pc()")
    public void error(){
        System.out.println("方法报错了");
    }
}

7.定义测试类进行增强类测试

import com.example.config.JavaConfig;
import com.example.service.impl.CalculatorPureImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

@SpringJUnitConfig(value = JavaConfig.class)
public class SpringAopTest {
    // aop - 代理 - jdk - 接口 - 代理类  - 代理对象和目标对象 拜把子 兄弟关系 - 接口接值
    // 有aop - 在ioc中存储的是代理对象
    @Autowired
    private CalculatorPureImpl calculator;
    
    @Test
    public void test(){
        System.out.println("add = " + calculator.div(1, 1));
    }

}

8.获取目标方法信息并环绕通知方式

方法信息(方法名,参数,访问修饰符,所属的类的信息...)

 注意包为:import org.aspectj.lang.JoinPoint;

package com.example.advice;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import java.util.logging.Logger;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.util.Arrays;

/**
 * description:环绕通知,需要你在通知中,定义目标方法的执行!
 */
@Component
@Aspect
@Order(5)
public class TxAroundAdvice {
    private static Logger log = Logger.getLogger(TxAroundAdvice.class.toString());
// 使用@Around注解标明环绕通知方法
    @Around(value = "com.example.pointcut.MyPointCut.pc()")
    public Object manageTransaction(// 通过在通知方法形参位置声明ProceedingJoinPoint类型的形参,Spring会将这个类型的对象传给我们
            ProceedingJoinPoint joinPoint) {
        // 通过ProceedingJoinPoint对象获取外界调用目标方法时传入的实参数组
        Object[] args = joinPoint.getArgs();

        // 通过ProceedingJoinPoint对象获取目标方法的签名对象
        Signature signature = joinPoint.getSignature();

        // 通过签名对象获取目标方法的方法名
        String methodName = signature.getName();

        // 声明变量用来存储目标方法的返回值
        Object targetMethodReturnValue = null;

        try {
            // 在目标方法执行前:开启事务(模拟)
            log.info("[AOP 环绕通知] 开启事务,方法名:" + methodName + ",参数列表:" + Arrays.asList(args));

            // 过ProceedingJoinPoint对象调用目标方法
            // 目标方法的返回值一定要返回给外界调用者
            targetMethodReturnValue = joinPoint.proceed(args);

            // 在目标方法成功返回后:提交事务(模拟)
            log.info("[AOP 环绕通知] 提交事务,方法名:" + methodName + ",方法返回值:" + targetMethodReturnValue);
        }catch (Throwable e){
            // 在目标方法抛异常后:回滚事务(模拟)
            log.info("[AOP 环绕通知] 回滚事务,方法名:" + methodName + ",异常:" + e.getClass().getName());
        }finally {
            // 在目标方法最终结束后:释放数据库连接
            log.info("[AOP 环绕通知] 释放数据库连接,方法名:" + methodName);
        }
        return targetMethodReturnValue;
    }
}

 运行测试

 

相关推荐

  1. Spring AOP 切面编程

    2024-03-19 20:58:02       37 阅读
  2. Spring aop切面编程

    2024-03-19 20:58:02       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-19 20:58:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-19 20:58:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-03-19 20:58:02       87 阅读
  4. Python语言-面向对象

    2024-03-19 20:58:02       96 阅读

热门阅读

  1. 在Swift中集成Socket.IO进行实时通信

    2024-03-19 20:58:02       43 阅读
  2. 【NLP11-迁移学习】

    2024-03-19 20:58:02       39 阅读
  3. Jenkins: 搭建Jenkins服务,调通Webhook链路

    2024-03-19 20:58:02       43 阅读
  4. LlamaParse: 高效的PDF文件RAG解析工具

    2024-03-19 20:58:02       43 阅读
  5. 强缓存和协商缓存的区别

    2024-03-19 20:58:02       40 阅读
  6. leetcode303--区域和检索

    2024-03-19 20:58:02       41 阅读