Spring AOP之MethodInterceptor原理

简介: 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会根据是否执行目标方法而在前后执行,还可以控制目标方法的执行。

偷了一张图,可以参考一下:

来源: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()调用下一级,并在前/后执行本拦截器的通知逻辑,形成完整的通知调用链。

目录
相关文章
|
1月前
|
Java
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
这篇文章是Spring5框架的实战教程,深入讲解了AOP的基本概念、如何利用动态代理实现AOP,特别是通过JDK动态代理机制在不修改源代码的情况下为业务逻辑添加新功能,降低代码耦合度,并通过具体代码示例演示了JDK动态代理的实现过程。
Spring5入门到实战------9、AOP基本概念、底层原理、JDK动态代理实现
|
6天前
|
Java 数据库连接 数据库
Spring基础3——AOP,事务管理
AOP简介、入门案例、工作流程、切入点表达式、环绕通知、通知获取参数或返回值或异常、事务管理
Spring基础3——AOP,事务管理
|
1月前
|
XML Java 数据格式
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
这篇文章是Spring5框架的AOP切面编程教程,通过XML配置方式,详细讲解了如何创建被增强类和增强类,如何在Spring配置文件中定义切入点和切面,以及如何将增强逻辑应用到具体方法上。文章通过具体的代码示例和测试结果,展示了使用XML配置实现AOP的过程,并强调了虽然注解开发更为便捷,但掌握XML配置也是非常重要的。
Spring5入门到实战------11、使用XML方式实现AOP切面编程。具体代码+讲解
|
1月前
|
XML Java 数据格式
Spring5入门到实战------2、IOC容器底层原理
这篇文章深入探讨了Spring5框架中的IOC容器,包括IOC的概念、底层原理、以及BeanFactory接口和ApplicationContext接口的介绍。文章通过图解和实例代码,解释了IOC如何通过工厂模式和反射机制实现对象的创建和管理,以及如何降低代码耦合度,提高开发效率。
Spring5入门到实战------2、IOC容器底层原理
|
19天前
|
缓存 Java 开发者
Spring高手之路22——AOP切面类的封装与解析
本篇文章深入解析了Spring AOP的工作机制,包括Advisor和TargetSource的构建与作用。通过详尽的源码分析和实际案例,帮助开发者全面理解AOP的核心技术,提升在实际项目中的应用能力。
17 0
Spring高手之路22——AOP切面类的封装与解析
|
19天前
|
Java Spring XML
掌握面向切面编程的秘密武器:Spring AOP 让你的代码优雅转身,横切关注点再也不是难题!
【8月更文挑战第31天】面向切面编程(AOP)通过切面封装横切关注点,如日志记录、事务管理等,使业务逻辑更清晰。Spring AOP提供强大工具,无需在业务代码中硬编码这些功能。本文将深入探讨Spring AOP的概念、工作原理及实际应用,展示如何通过基于注解的配置创建切面,优化代码结构并提高可维护性。通过示例说明如何定义切面类、通知方法及其应用时机,实现方法调用前后的日志记录,展示AOP在分离关注点和添加新功能方面的优势。
30 0
|
28天前
|
缓存 安全 Java
Spring AOP 中两种代理类型的限制
【8月更文挑战第22天】
13 0
|
28天前
|
Java Spring
|
1月前
|
XML Java 数据库
Spring5入门到实战------10、操作术语解释--Aspectj注解开发实例。AOP切面编程的实际应用
这篇文章是Spring5框架的实战教程,详细解释了AOP的关键术语,包括连接点、切入点、通知、切面,并展示了如何使用AspectJ注解来开发AOP实例,包括切入点表达式的编写、增强方法的配置、代理对象的创建和优先级设置,以及如何通过注解方式实现完全的AOP配置。
|
Java Spring
Spring原理学习系列之五:IOC原理之Bean加载
其实很多同学都想通过阅读框架的源码以汲取框架设计思想以及编程营养,Spring框架其实就是个很好的框架源码学习对象。我们都知道Bean是Spring框架的最小操作单元,Spring框架通过对于Bean的统一管理实现其IOC以及AOP等核心的框架功能,那么Spring框架是如何把Bean加载到环境中来进行管理的呢?本文将围绕这个话题进行详细的阐述,并配合Spring框架的源码解析。
Spring原理学习系列之五:IOC原理之Bean加载