获取通知的相关信息

Last updated: ... / Reads: 37 Edit

在Spring AOP中,你可以通过在通知方法中使用特定的参数来获取通知的相关信息。Spring AOP支持一些特定的参数类型,这些参数会在运行时由Spring容器注入,以提供与当前通知执行上下文相关的信息。以下是一些常用的通知参数类型:

  1. JoinPoint: JoinPoint 提供有关连接点(被通知的方法执行)的信息,例如方法名称、目标对象、方法参数等。

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("Before executing: " + joinPoint.getSignature().toShortString());
    }
    
  2. ProceedingJoinPoint: ProceedingJoinPointJoinPoint 的子类,用于Around通知。它包含了能够执行目标方法的 proceed() 方法。

    @Around("execution(* com.example.service.*.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("Before executing: " + proceedingJoinPoint.getSignature().toShortString());
        Object result = proceedingJoinPoint.proceed();
        System.out.println("After executing: " + proceedingJoinPoint.getSignature().toShortString());
        return result;
    }
    
  3. JoinPoint.StaticPart: 通过 StaticPart 可以获取与连接点相关的静态信息,如源代码位置。

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeAdvice(JoinPoint.StaticPart staticPart) {
        System.out.println("Before executing at: " + staticPart.getSourceLocation());
    }
    

这些参数类型可以根据需要在通知方法中选择使用。通过这些参数,你可以获取关于被通知方法的各种信息,使得在通知中能够处理更多的上下文信息。


Comments

Make a comment