Spring AOP之MethodInterceptor原理

引言

之前我们讨论过了HandlerInterceptor,现在我们来看一下MethodInterceptor。
MethodInterceptor是Spring AOP中的一个重要接口,用来拦截方法调用,它只有一个invoke方法。

Spring AOP组成

  1. Aspect:切面,是一个普通的Java类,里面定义了通知(Advice)和切点(Pointcut)。
  2. Advice:通知,定义了切面要织入目标对象的具体时机和操作。有前置通知、后置通知、异常通知、最终通知和环绕通知等。
  3. Pointcut:切点,指明应用通知的具体对象和方法。可以通过表达式或匹配命名规范来指定切点。
  4. Target:目标对象,被通知和切点织入额对象。
  5. Weaving:织入,将切面应用到目标对象来创建代理对象的过程。Spring AOP中通常在运行期间通过动态代理来实现。

先看一下Advice

Spring AOP支持5种类型的Advice(通知),执行时机和简单解释如下:

通知名执行时机解释
@Before目标方法执行前在目标方法执行前执行,可以用于方法级预处理
@AfterReturning目标方法执行后,且没有异常用于方法后置处理,获取方法返回值等
@After目标方法执行后,不论方法异常与否用于资源清理
@AfterThrowing目标方法抛出异常后处理方法中抛出的异常
@Around环绕目标方法在目标方法执行前后都可以执行自定义操作,并控制目标方法是否执行及其参数

这5种Advice的执行顺序如下:

  1. @Before:前置通知,目标方法执行之前执行
  2. @Around:环绕通知, encloses 目标方法,在目标方法之前和之后执行自定义操作
  3. 目标方法执行
  4. @AfterReturning:返回通知,目标方法成功执行之后执行
  5. @AfterThrowing:异常通知,目标方法抛出异常后执行
  6. @After:后置通知,目标方法之后执行
    所以总结来说:
    @Before,@After在目标方法执行前后一定会执行。
    @AfterReturning只有目标方法成功执行后才会执行。
    @AfterThrowing只有目标方法抛出异常后才会执行。
    @Around会根据是否执行目标方法而在前后执行,还可以控制目标方法的执行。

偷了一张图,可以参考一下:
来源:https://zhuanlan.zhihu.com/p/500555634
来源:Spring AOP通知(Advice)详解

示例

我们直接来个例子
pom文件,我用的gradle:

plugins {
    id 'org.springframework.boot' version '3.0.2'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '17'


repositories {
    mavenLocal()
    maven { url "https://maven.aliyun.com/nexus/content/groups/public/"}
    mavenCentral()
    jcenter()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
    maven { url 'https://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}


dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    implementation 'org.springframework.boot:spring-boot-starter-aop'
}

service接口和类

public interface ExampleService {
    void doSomething();

    void doAnything();


    void justPlay();
}

@Service
public class ExampleServiceImpl implements ExampleService {
    @Override
    public void doSomething() {
        System.out.println("-----------doSomething ----------");
    }    
	
	@Override
    public void doAnything() {
        System.out.println("-----------doAnything ----------");

    }

    @Override
    public void justPlay() {
        System.out.println("-----------justPlay ----------");

    }
}

切面类:

@Aspect
@Component
public class ExampleAspect {

//只拦截do开头的方法
    @Before("execution(* com.example.gspringtest.service.impl.ExampleServiceImpl.do*(..))")
    public void beforeMethod() {
        System.out.println("Before method");
    }
}

测试接口:


package com.example.gspringtest.demos.web;

import com.example.gspringtest.service.ExampleService;
import com.example.gspringtest.service.impl.ExampleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author <a href="mailto:chenxilzx1@gmail.com">theonefx</a>
 */
@Controller
public class BasicController {

    @Autowired
    private ExampleService exampleService;
    @Autowired
    private ApplicationContext applicationContext;

    @RequestMapping("/testMethod")
    @ResponseBody
    public String testMethod() {
        exampleService.doSomething();

        System.out.println("******************888888888********************");

        exampleService.doAnything();

        System.out.println("******************888888888********************");

        exampleService.justPlay();
//        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        ExampleService exampleService1 = applicationContext.getBean(ExampleServiceImpl.class);
        ExampleServiceImpl exampleService2 = applicationContext.getBean(ExampleServiceImpl.class);

        return "Hello " ;
    }
}

先来看一下输出

Before method
-----------doSomething ----------
******************888888888********************
Before method
-----------doAnything ----------
******************888888888********************
-----------justPlay ----------

提问

请告诉我,测试接口中的exampleService,exampleService1和exampleService2是同一个bean吗?是代理类还是原对象?

来揭晓一下答案:

首先是同一个bean
在这里插入图片描述
其次,只能拿到代理类:
在这里插入图片描述

原理

上面讲了这么多,好像跟MethodInterceptor没啥关系啊,我们
先来看几个类:

MethodBeforeAdviceAdapter
执行Before方法

AfterReturningAdviceInterceptor
执行AfterReturning方法

ThrowsAdviceInterceptor
执行AfterThrowing方法

AspectJAfterAdvice
执行Aftor方法

AspectJAroundAdvice
执行Around方法

这几个类都实现了MethodIntercepter,并且分别对应了不同的通知类型。

spring aop为目标对象生成的代理对象是通过实现MethodInterceptor接口来与拦截器协同工作的。

代理对象通过实现MethodInterceptor接口并协调拦截器链,与各MethodInterceptor实现相结合,最终执行完所有相关通知逻辑并将结果返回给客户端。
拦截器链中的每个拦截器通过mi.proceed()调用下一级,并在前/后执行本拦截器的通知逻辑,形成完整的通知调用链。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

盖丽男

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

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

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

打赏作者

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

抵扣说明:

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

余额充值