package com.tedu.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
/**
* 要想把一个类变成切面类,需要两步:
* ① 在类上使用 @Component 注解 把切面类加入到IOC容器中
* ② 在类上使用 @Aspect 注解 使之成为切面类
*/
@Component // 把这个类交给spring管理
@Aspect // 表示这是一个切面类
public class UserAspect {
@Pointcut("@annotation(com.tedu.keys)")
private void pointCut1() {}
//@Around("execution(* com.tedu.controller.UserController.getUserById(..))")
//@Around(value = "pointCut1()")
// 这个方法的里面不可以同时传入ProceedingJoinPoint和Joinpoint,因为ProceedingJoinPoint为Joinpoint的子类
// 相关获取的方法可以用ProceedingJoinPoint这个类的对象来获取。
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("这个是前置增强!" + joinPoint.getSignature().getName());
Object object = joinPoint.proceed();
System.out.println("这个是后置增强!");
return object;
}
//@Before("@annotation(com.tedu.keys)")
public void before() {
System.out.println("这个是在目标方法执行之前执行的通知!!");
}
// 其他方法的返回值是void就可以啦,只有环绕通知的返回值为Object类型的。
// @AfterReturning(value = "pointCut1()",returning = "ret")
public void afterReturing(Object ret) { // 接受返回值类型的也是Object因为可以返回任何的类型。
System.out.println("这个是在方法返回之后执行,可以接受到方法的返回值:" + ret);
}
// 异常抛出通知 // 这个是有异常的时候才会执行,没有异常的时候是不会执行的,一般情况下需要定义一个需要接收异常信息的返回值
//@AfterThrowing(value = "pointCut1()",throwing = "e")
public void throwing(Throwable e) {
System.out.println("这是一个异常抛出通知可以用来返回异常信息" + e.getMessage());
}
// 这个是最终通知不管有没有异常都会执行这个方法
@After("pointCut1()")
public void after() {
System.out.println("这个是最终通知到了最后都会执行这个方法");
}
}
``
AOP问题总结
最新推荐文章于 2025-03-01 00:23:37 发布