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容器中)
目录
相关文章
|
1月前
|
XML Java 开发者
Spring Boot中的AOP实现
Spring AOP(面向切面编程)允许开发者在不修改原有业务逻辑的情况下增强功能,基于代理模式拦截和增强方法调用。Spring Boot通过集成Spring AOP和AspectJ简化了AOP的使用,只需添加依赖并定义切面类。关键概念包括切面、通知和切点。切面类使用`@Aspect`和`@Component`注解标注,通知定义切面行为,切点定义应用位置。Spring Boot自动检测并创建代理对象,支持JDK动态代理和CGLIB代理。通过源码分析可深入了解其实现细节,优化应用功能。
|
14天前
|
XML Java 测试技术
Spring AOP—通知类型 和 切入点表达式 万字详解(通俗易懂)
Spring 第五节 AOP——切入点表达式 万字详解!
73 25
|
14天前
|
XML 安全 Java
Spring AOP—深入动态代理 万字详解(通俗易懂)
Spring 第四节 AOP——动态代理 万字详解!
66 24
|
1月前
|
存储 安全 Java
Spring Boot 3 集成Spring AOP实现系统日志记录
本文介绍了如何在Spring Boot 3中集成Spring AOP实现系统日志记录功能。通过定义`SysLog`注解和配置相应的AOP切面,可以在方法执行前后自动记录日志信息,包括操作的开始时间、结束时间、请求参数、返回结果、异常信息等,并将这些信息保存到数据库中。此外,还使用了`ThreadLocal`变量来存储每个线程独立的日志数据,确保线程安全。文中还展示了项目实战中的部分代码片段,以及基于Spring Boot 3 + Vue 3构建的快速开发框架的简介与内置功能列表。此框架结合了当前主流技术栈,提供了用户管理、权限控制、接口文档自动生成等多项实用特性。
81 8
|
3月前
|
XML Java 数据安全/隐私保护
Spring Aop该如何使用
本文介绍了AOP(面向切面编程)的基本概念和术语,并通过具体业务场景演示了如何在Spring框架中使用Spring AOP。文章详细解释了切面、连接点、通知、切点等关键术语,并提供了完整的示例代码,帮助读者轻松理解和应用Spring AOP。
Spring Aop该如何使用
|
3月前
|
监控 安全 Java
什么是AOP?如何与Spring Boot一起使用?
什么是AOP?如何与Spring Boot一起使用?
111 5
|
3月前
|
Java 开发者 Spring
深入解析:Spring AOP的底层实现机制
在现代软件开发中,Spring框架的AOP(面向切面编程)功能因其能够有效分离横切关注点(如日志记录、事务管理等)而备受青睐。本文将深入探讨Spring AOP的底层原理,揭示其如何通过动态代理技术实现方法的增强。
103 8
|
3月前
|
Java 开发者 Spring
Spring AOP 底层原理技术分享
Spring AOP(面向切面编程)是Spring框架中一个强大的功能,它允许开发者在不修改业务逻辑代码的情况下,增加额外的功能,如日志记录、事务管理等。本文将深入探讨Spring AOP的底层原理,包括其核心概念、实现方式以及如何与Spring框架协同工作。
|
3月前
|
XML 监控 安全
深入调查研究Spring AOP
【11月更文挑战第15天】
62 5
|
3月前
|
Java 开发者 Spring
Spring AOP深度解析:探秘动态代理与增强逻辑
Spring框架中的AOP(Aspect-Oriented Programming,面向切面编程)功能为开发者提供了一种强大的工具,用以将横切关注点(如日志、事务管理等)与业务逻辑分离。本文将深入探讨Spring AOP的底层原理,包括动态代理机制和增强逻辑的实现。
72 4