Spring中使用AspectJ实现AOP的五种通知

简介: Spring中使用AspectJ实现AOP的五种通知

【1】AOP通知方法

通知方法可以简单理解为标注有某种注解的简单的 Java 方法,在目标方法执行时的某个位置(时机)进行执行。

AspectJ 支持 5 种类型的通知


@Before: 前置通知, 在方法执行之前执行,这个通知不能阻止连接点前的执行(除非它抛出一个异常)。


@After: 后置通知, 在方法执行之后执行(不论是正常返回还是异常退出)。


@AfterRunning:返回通知, 在方法正常返回结果之后执行 。


@AfterThrowing: 异常通知, 在方法抛出异常之后。


@Around: 包围一个连接点(join point)的通知,如方法调用。这是最强大的一种通知类型。 环绕通知可以在方法调用前后完成自定义的行为。它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行。


在 Spring 中声明 AspectJ 切面, 需要在 IOC 容器中将切面类声明为 Bean 实例(可以使用注解或者手动在xml中注册bean)。


当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面类中方法上面切入点注解相匹配的 Bean 创建代理。


在 AspectJ 注解中, 切面只是一个带有 @Aspect 注解的 Java 类。

让通知访问当前连接点的细节

可以在通知方法中声明一个类型为 JoinPoint 的参数. 然后就能访问链接细节:如方法名称和参数值。


注解使用的JAR和xml配置

要在 Spring 应用中使用 AspectJ 注解, 必须在 classpath 下包含 AspectJ 类库:

aopalliance.jar、aspectj.weaver.jar 和 spring-aspects.jar


将 aop Schema 添加到<beans>根元素中.

xmlns:aop="http://www.springframework.org/schema/aop"

在 Bean 配置文件中定义一个空的 XML 元素 <aop:aspectj-autoproxy>


当 Spring IOC 容器侦测到 Bean 配置文件中的 <aop:aspectj-autoproxy> 元素时, 会自动为与 AspectJ 切面匹配的 Bean 创建代理.

<!-- **使Aspect注解起作用,自动为匹配的类生产代理对象** -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

也可以在SpringBoot环境下使用@EnableAspectJAutoProxy(proxyTargetClass = true)注解启用。

定义切点表达式方法,使其可以多处使用

定义一个方法,用于声明切入点表达式。 一般的,该方法中再不需要添入其他的代码;使用@Pointcut来声明切入点表达式;后面的其他通知直接使用方法名来引用当前的切入点表达式

@Pointcut("execution(int com.web.aop.impl.ArithmeticCalculatorImpl.*(int , int ))")
public void declareJoinPointExpression() {
}

【2】五种通知

① 前置通知

前置通知:在方法执行之前执行的通知。前置通知使用 @Before 注解, 并将切入点表达式的值作为注解值.

@Before("declareJoinPointExpression()")
public void beforMethod(JoinPoint joinPoint){
  /*获取方法名*/
  String methodName = joinPoint.getSignature().getName();
  /*获取方法的参数*/
  List<Object> args = Arrays.asList(joinPoint.getArgs());
  System.out.println("The method "+methodName+" begins with"+args);
}

外部类切入点表达式方法引用如下:

使用类全路径+方法名

@Before("com.web.aop.LogAspects.pointCut()")
public void logEnd(JoinPoint joinPoint){
  System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
}

② 后置通知

后置通知:在目标方法执行后执行,无论是否抛出异常。后置通知中不能访问目标方法执行后返回的结果。

@After("execution(* com.web.aop.impl.*.*(int , int ))")
/*表示该包下所有返回类型的所有类的所有方法*/
public void afterMethod(JoinPoint joinPoint){
  /*获取方法名*/
  String methodName = joinPoint.getSignature().getName();
  /*获取方法的参数*/
  List<Object> args = Arrays.asList(joinPoint.getArgs());
  System.out.println("The method "+methodName+" ends with"+args);
}

③ 返回通知

返回通知 :在方法正常执行返回结果后执行,返回通知可以获取目标方法的返回值

在返回通知中, 只要将 returning 属性添加到 @AfterReturning 注解中, 就可以访问连接点的返回值。 该属性的值即为用来传入返回值的参数名称。

必须在通知方法的签名中添加一个同名参数,在运行时Spring AOP 会通过这个参数传递返回值。

原始的切点表达式需要出现在 pointcut 属性中。

@AfterReturning(pointcut="execution(* com.web.aop.impl.*.*(int , int ))",returning="result")
/*表示该包下所有返回类型的所有类的所有方法*/
public void afterReturning(JoinPoint joinPoint ,Object result){
  /*获取方法名*/
  String methodName = joinPoint.getSignature().getName();
  /*获取方法的参数*/
  List<Object> args = Arrays.asList(joinPoint.getArgs());
  System.out.println("The method "+methodName+" ends with "+result);
}

④ 异常通知

在方法抛出异常后执行,可以访问到异常对象。且可以指定在出现特定异常对象时,再执行。


只在连接点抛出异常时才执行异常通知

将 throwing 属性添加到 @AfterThrowing 注解中, 也可以访问连接点抛出的异常.

Throwable 是所有错误和异常类的超类. 所以在异常通知方法可以捕获到任何错误和异常.


如果只对某种特殊的异常类型感兴趣, 可以将参数声明为其他异常的参数类型. 然后通知就只在抛出这个类型及其子类的异常时才被执行。

@AfterThrowing(value="execution(* com.web.aop.impl.*.*(int , int ))",throwing="exception")
/*表示该包下所有返回类型的所有类的所有方法*/
public void afterThrowing(JoinPoint joinPoint ,Exception exception){
  /*获取方法名*/
  String methodName = joinPoint.getSignature().getName();
  /*获取方法的参数*/
  List<Object> args = Arrays.asList(joinPoint.getArgs());
  System.out.println("The method "+methodName+" throws exception :"+exception);
}


⑤ 环绕通知

环绕通知是所有通知类型中功能最为强大的, 能够全面地控制连接点. 甚至可以控制是否执行连接点.动态代理,手动推进目标方法运行(joinPoint.procced())


环绕通知需要携带ProceedingJoinPoint类型的参数;


环绕通知类似于动态代理的全过程:ProceedingJoinPoint类型的参数可以决定是否执行目标方法;


环绕通知必须有返回值,返回值即为目标方法的返回值 !


对于环绕通知来说, 连接点的参数类型必须是 ProceedingJoinPoint 。它是 JoinPoint 的子接口, 允许控制何时执行, 是否执行连接点。


在环绕通知中需要明确调用 ProceedingJoinPoint 的 proceed() 方法来执行被代理的方法。 如果忘记这样做就会导致通知被执行了, 但目标方法没有被执行。

  • 注意: 环绕通知的方法需要返回目标方法执行之后的结果, 即调用 joinPoint.proceed() 的返回值, 否则会出现空指针异常。
@Around("execution(* com.web.aop.impl.*.*(int , int ))")
/*表示该包下所有返回类型的所有类的所有方法*/
public Object aroundMethod(ProceedingJoinPoint joinPoint){
  System.out.println("This is aroundMethod....");
  /*获取方法名*/
  String methodName = joinPoint.getSignature().getName();
  /*获取方法的参数*/
  List<Object> args = Arrays.asList(joinPoint.getArgs());
  Object result = null;
  try {
    //前置通知
    System.out.println("The method "+methodName+" begins with  :"+args);
    result = joinPoint.proceed();
    //返回通知
    System.out.println();
    System.out.println("The method "+methodName+" ends with  :"+result);
  } catch (Throwable e) {
    // 异常通知
    System.out.println("The method "+methodName+" throws exception :"+e);
    throw new RuntimeException(e);
  }
  //后置通知
  System.out.println("The method "+methodName+" ends ");
  return result;  
}

当@Around与@Before同时存在时,则会先执行@Around中方法,当执行到point.proceed()时,会触发@Before的方法。


【3】无配置文件方式使用AOP注解

去掉xml配置文件,使用配置类的方式。@EnableAspectJAutoProxy注解:开启基于注解的aop模式。配置类如下:

@EnableAspectJAutoProxy
@Configuration
public class MainConfigOfAOP {
  //业务逻辑类加入容器中
  @Bean
  public MathCalculator calculator(){
    return new MathCalculator();
  }
  //切面类加入到容器中
  @Bean
  public LogAspects logAspects(){
    return new LogAspects();
  }
}

切面类如下:

/**
 * 切面类
 * @Aspect: 告诉Spring当前类是一个切面类
 */
@Aspect
public class LogAspects {
  //抽取公共的切入点表达式
  //1、本类引用
  //2、其他的切面引用
  @Pointcut("execution(public int com.web.aop.MathCalculator.*(..))")
  public void pointCut(){};
  //@Before在目标方法之前切入;切入点表达式(指定在哪个方法切入)
  @Before("pointCut()")
  public void logStart(JoinPoint joinPoint){
    Object[] args = joinPoint.getArgs();
    System.out.println(""+joinPoint.getSignature().getName()+"运行。。。@Before:参数列表是:{"+Arrays.asList(args)+"}");
  }
  @After("com.web.aop.LogAspects.pointCut()")
  public void logEnd(JoinPoint joinPoint){
    System.out.println(""+joinPoint.getSignature().getName()+"结束。。。@After");
  }
  //JoinPoint一定要出现在参数表的第一位
  @AfterReturning(value="pointCut()",returning="result")
  public void logReturn(JoinPoint joinPoint,Object result){
    System.out.println(""+joinPoint.getSignature().getName()+"正常返回。。。@AfterReturning:运行结果:{"+result+"}");
  }
  @AfterThrowing(value="pointCut()",throwing="exception")
  public void logException(JoinPoint joinPoint,Exception exception){
    System.out.println(""+joinPoint.getSignature().getName()+"异常。。。异常信息:{"+exception+"}");
  }
}

目标类如下:

public class MathCalculator {
  public int div(int i,int j){
    System.out.println("MathCalculator...div...");
    return i/j; 
  }
}

测试类如下:

public class IOCTest_AOP {
  @Test
  public void test01(){
    AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfigOfAOP.class);
//1、不要自己创建对象,只有Spring容器中的bean,才能使用Spring AOP提供的功能
//    MathCalculator mathCalculator = new MathCalculator();
//    mathCalculator.div(1, 1);
    MathCalculator mathCalculator = applicationContext.getBean(MathCalculator.class);
    mathCalculator.div(1, 0);
    applicationContext.close();
  }
}

测试结果如下:

信息: JSR-330 'javax.inject.Inject' annotation found and supported 
for autowiring
div运行。。。@Before:参数列表是:{[1, 0]}
MathCalculator...div...
div结束。。。@After
div异常。。。异常信息:{java.lang.ArithmeticException: / by zero}

通知的执行顺序

正常执行:前置通知—目标方法—后置通知—返回通知

出现异常:前置通知—目标方法—后置通知—异常通知


【4】纯xml方式实现通知


除了使用 AspectJ 注解声明切面, Spring 也支持在 Bean 配置文件中声明切面。 这种声明是通过 aop schema 中的 XML 元素完成的。


正常情况下, 基于注解的声明要优先于基于 XML 的声明。通过 AspectJ 注解, 切面可以与 AspectJ 兼容, 而基于 XML 的配置则是 Spring 专有的。由于 AspectJ 得到越来越多的AOP 框架支持, 所以以注解风格编写的切面将会有更多重用的机会。


声明切面


要在 Spring 中声明 AspectJ 切面, 只需要在 IOC 容器中将切面声明为 Bean 实例。 当在 Spring IOC 容器中初始化 AspectJ 切面之后, Spring IOC 容器就会为那些与 AspectJ 切面相匹配的 Bean 创建代理。


当使用 XML 声明切面时, 需要在 <beans> 根元素中导入 aop Schema。在 Bean 配置文件中, 所有的 Spring AOP 配置都必须定义在 <aop:config> 元素内部。对于每个切面而言, 都要创建一个 <aop:aspect> 元素来为具体的切面实现引用后端 Bean 实例。


切面 Bean 必须有一个标示符, 供 <aop:aspect> 元素引用。


定义切入点


切入点使用 <aop:pointcut> 元素声明。切入点必须定义在 <aop:aspect> 元素下, 或者直接定义在 <aop:config> 元素下。


定义在 <aop:aspect> 元素下: 只对当前切面有效

定义在 aop:config 元素下: 对所有切面都有效

基于 XML 的 AOP 配置不允许在切入点表达式中用名称引用其他切入点。声明通知

在 aop Schema 中, 每种通知类型都对应一个特定的 XML 元素。通知元素需要使用 <pointcut-ref> 来引用切入点, 或用 <pointcut> 直接嵌入切入点表达式。 method 属性指定切面类中通知方法的名称。

<!-- *************以下使用xml配置***************-->
<!-- 配置目标bean -->
<bean id="arithmeticCalculator" class="com.web.aop.impl.xml.ArithmeticCalculatorImpl"></bean>
<!-- 配置切面bean -->
<bean id="loggingAspect" class="com.web.aop.impl.xml.LoggingAspect"></bean>
<bean id="validateAspect" class="com.web.aop.impl.xml.ValidateAspect"></bean>
<!-- ******************************AOP 配置******************************* -->
<aop:config>
    <!-- 配置切点表达式 -->
    <aop:pointcut id="pointcut" expression="execution(* com.web.aop.impl.xml.ArithmeticCalculatorImpl.*(int, int))" />
    <!-- 配置日志切面 -->
    <aop:aspect  ref="loggingAspect" order="1" >
        <aop:before method="beforMethod" pointcut-ref="pointcut"/>
        <aop:after method="afterMethod" pointcut-ref="pointcut"/>
        <aop:after-returning method="afterReturning" pointcut-ref="pointcut" returning="result"/>
        <aop:after-throwing method="afterThrowing" pointcut-ref="pointcut" throwing="exception"/>
        <aop:around method="aroundMethod" pointcut-ref="pointcut" />
    </aop:aspect>
    <!-- 配置验证切面 -->
    <aop:aspect  ref="validateAspect" order="2" >
        <aop:before method="beforMethod" pointcut-ref="pointcut"/>
    </aop:aspect>
</aop:config>


声明引入

可以利用 <aop:declare-parents> 元素在切面内部声明引入。


【5】引入通知


Spring AOP提供的@Before、@After、@AfterReturning、@AfterThrowing、Around只对类的现有方法进行增强处理。如果需要对现有类增加新的方法而不改动目标类的代码,则可以使用引入通知。


引入通知是一种特殊的通知类型。它通过为接口提供实现类, 允许对象动态地实现接口, 就像对象已经在运行时扩展了实现类一样。


引入通知的声明


在切面中, 通过为任意字段添加@DeclareParents 注解来引入声明.。注解类型的 value 属性表示哪些类是当前引入通知的目标。value 属性值也可以是一个 AspectJ 类型的表达式, 以将一个即可引入到多个类中。 defaultImpl 属性中指定这个接口使用的实现类。

@Aspect
@Component
public class LogAspect {
// 引入通知
    @DeclareParents(value = "com.recommend.controller.HomeController",defaultImpl=MyDeclareImpl.class)
    private MyDeclareService myDeclareService;
    @Pointcut("execution(* com.recommend.controller.*.*(..))")
    public void logPointCut() {
    }
    @Before(value = "execution(* com.recommend.controller.*.*(..))")
    public void beforeMethod(JoinPoint point)  {
        System.out.println(" before(Joinpoint point)");
    }
    @After("logPointCut()")
    public void afterMethod(JoinPoint point)  {
        System.out.println(" afterMethod(Joinpoint point)");
    }
    @AfterReturning(pointcut = "logPointCut()",returning="result")
    public void AfterReturning(JoinPoint point,Object result)  {
        System.out.println(" AfterReturning(Joinpoint point)");
    }
    @AfterThrowing(value = "logPointCut()",throwing="exception")
    public void AfterThrowing(JoinPoint point,Exception exception)  {
        System.out.println(" AfterThrowing(Joinpoint point)");
    }
    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        // 执行方法
        Object result = point.proceed();
        // 执行时长(毫秒)
        long time = System.currentTimeMillis() - beginTime;
        //异步保存日志
        return result;
    }
}

也可以通过xml配置实现

如下图所示xml配置示例:

417ad3c778cf4f8e9f4f9cc970f90878.png


  • types-matching:待增强类的表达式,支持通配符
  • implement-interface:引入增强的方法所在的接口
  • default-impl:引入增强的实现类的全路径名称(使用该方式无需把增强类的Bean注入到Spring容器中)
目录
相关文章
|
17天前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
228 0
|
4月前
|
监控 安全 Java
Spring AOP实现原理
本内容主要介绍了Spring AOP的核心概念、实现机制及代理生成流程。涵盖切面(Aspect)、连接点(Join Point)、通知(Advice)、切点(Pointcut)等关键概念,解析了JDK动态代理与CGLIB代理的原理及对比,并深入探讨了通知执行链路和责任链模式的应用。同时,详细分析了AspectJ注解驱动的AOP解析过程,包括切面识别、切点表达式匹配及通知适配为Advice的机制,帮助理解Spring AOP的工作原理与实现细节。
|
29天前
|
人工智能 监控 安全
Spring AOP切面编程颠覆传统!3大核心注解+5种通知类型,让业务代码纯净如初
本文介绍了AOP(面向切面编程)的基本概念、优势及其在Spring Boot中的使用。AOP作为OOP的补充,通过将横切关注点(如日志、安全、事务等)与业务逻辑分离,实现代码解耦,提升模块化程度、可维护性和灵活性。文章详细讲解了Spring AOP的核心概念,包括切面、切点、通知等,并提供了在Spring Boot中实现AOP的具体步骤和代码示例。此外,还列举了AOP在日志记录、性能监控、事务管理和安全控制等场景中的实际应用。通过本文,开发者可以快速掌握AOP编程思想及其实践技巧。
|
1月前
|
人工智能 监控 安全
如何快速上手【Spring AOP】?核心应用实战(上篇)
哈喽大家好吖~欢迎来到Spring AOP系列教程的上篇 - 应用篇。在本篇,我们将专注于Spring AOP的实际应用,通过具体的代码示例和场景分析,帮助大家掌握AOP的使用方法和技巧。而在后续的下篇中,我们将深入探讨Spring AOP的实现原理和底层机制。 AOP(Aspect-Oriented Programming,面向切面编程)是Spring框架中的核心特性之一,它能够帮助我们解决横切关注点(如日志记录、性能统计、安全控制、事务管理等)的问题,提高代码的模块化程度和复用性。
|
1月前
|
设计模式 Java 开发者
如何快速上手【Spring AOP】?从动态代理到源码剖析(下篇)
Spring AOP的实现本质上依赖于代理模式这一经典设计模式。代理模式通过引入代理对象作为目标对象的中间层,实现了对目标对象访问的控制与增强,其核心价值在于解耦核心业务逻辑与横切关注点。在框架设计中,这种模式广泛用于实现功能扩展(如远程调用、延迟加载)、行为拦截(如权限校验、异常处理)等场景,为系统提供了更高的灵活性和可维护性。
|
8月前
|
XML Java 开发者
Spring Boot中的AOP实现
Spring AOP(面向切面编程)允许开发者在不修改原有业务逻辑的情况下增强功能,基于代理模式拦截和增强方法调用。Spring Boot通过集成Spring AOP和AspectJ简化了AOP的使用,只需添加依赖并定义切面类。关键概念包括切面、通知和切点。切面类使用`@Aspect`和`@Component`注解标注,通知定义切面行为,切点定义应用位置。Spring Boot自动检测并创建代理对象,支持JDK动态代理和CGLIB代理。通过源码分析可深入了解其实现细节,优化应用功能。
407 6
|
7月前
|
XML Java 测试技术
Spring AOP—通知类型 和 切入点表达式 万字详解(通俗易懂)
Spring 第五节 AOP——切入点表达式 万字详解!
366 25
|
7月前
|
XML 安全 Java
Spring AOP—深入动态代理 万字详解(通俗易懂)
Spring 第四节 AOP——动态代理 万字详解!
267 24
|
6月前
|
Java API 微服务
微服务——SpringBoot使用归纳——Spring Boot中的切面AOP处理——Spring Boot 中的 AOP 处理
本文详细讲解了Spring Boot中的AOP(面向切面编程)处理方法。首先介绍如何引入AOP依赖,通过添加`spring-boot-starter-aop`实现。接着阐述了如何定义和实现AOP切面,包括常用注解如`@Aspect`、`@Pointcut`、`@Before`、`@After`、`@AfterReturning`和`@AfterThrowing`的使用场景与示例代码。通过这些注解,可以分别在方法执行前、后、返回时或抛出异常时插入自定义逻辑,从而实现功能增强或日志记录等操作。最后总结了AOP在实际项目中的重要作用,并提供了课程源码下载链接供进一步学习。
747 0
|
6月前
|
Java 开发者 微服务
微服务——SpringBoot使用归纳——Spring Boot中的切面AOP处理——什么是AOP
本文介绍了Spring Boot中的切面AOP处理。AOP(Aspect Oriented Programming)即面向切面编程,其核心思想是分离关注点。通过AOP,程序可以将与业务逻辑无关的代码(如日志记录、事务管理等)从主要逻辑中抽离,交由专门的“仆人”处理,从而让开发者专注于核心任务。这种机制实现了模块间的灵活组合,使程序结构更加可配置、可扩展。文中以生活化比喻生动阐释了AOP的工作原理及其优势。
347 0