AspectJ来实现时AOP切面类定义

49 阅读2分钟

当我们使用AspectJ来实现AOP时,我们需要定义一个切面类来描述我们要插入的横切关注点和切入点。一个切面类是一个普通的Java类,使用@Aspect注解来标记。在切面类中,我们可以定义切入点表达式和各种通知类型。

下面是一个使用AspectJ实现AOP的示例,其中定义了一个切面类来处理日志的记录:

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.MyClass.myMethod(..))")
    public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println("前置通知:目标方法执行前");
        System.out.println("目标方法:" + joinPoint.getSignature().getName());
    }

    @After("execution(* com.example.MyClass.myMethod(..))")
    public void afterAdvice(JoinPoint joinPoint) {
        System.out.println("后置通知:目标方法执行后");
        System.out.println("目标方法:" + joinPoint.getSignature().getName());
    }

    @AfterReturning(pointcut = "execution(* com.example.MyClass.myMethod(..))", returning = "result")
    public void afterReturningAdvice(JoinPoint joinPoint, Object result) {
        System.out.println("返回通知:目标方法成功执行并返回结果");
        System.out.println("目标方法:" + joinPoint.getSignature().getName());
        System.out.println("返回结果:" + result);
    }

    @AfterThrowing(pointcut = "execution(* com.example.MyClass.myMethod(..))", throwing = "exception")
    public void afterThrowingAdvice(JoinPoint joinPoint, Exception exception) {
        System.out.println("异常通知:目标方法抛出异常");
        System.out.println("目标方法:" + joinPoint.getSignature().getName());
        System.out.println("异常信息:" + exception.getMessage());
    }

    @Around("execution(* com.example.MyClass.myMethod(..))")
    public Object aroundAdvice(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        System.out.println("环绕通知:目标方法执行前");
        System.out.println("目标方法:" + proceedingJoinPoint.getSignature().getName());
        Object result = null;
        try {
            result = proceedingJoinPoint.proceed(); // 执行目标方法
            System.out.println("环绕通知:目标方法执行后");
        } catch (Exception e) {
            System.out.println("环绕通知:目标方法抛出异常");
            System.out.println("异常信息:" + e.getMessage());
        }
        return result;
    }
}

在上面的示例中,我们定义了一个切面类LoggingAspect,它使用@Aspect注解来标记为一个切面类,并使用@Component注解将其声明为一个Spring组件。

在切面类中,我们定义了五种不同的通知类型:前置通知(Before Advice)、后置通知(After Advice)、返回通知(After Returning Advice)、异常通知(After Throwing Advice)和环绕通知(Around Advice)。每种通知类型都使用了相应的注解,如@Before、@After、@AfterReturning、@AfterThrowing和@Around。

在每个通知方法中,我们可以通过JoinPoint参数获取到目标方法的信息,如方法名、参数等。我们还可以使用注解的属性来指定切入点表达式和其他相关信息。