AOP问题总结

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("这个是最终通知到了最后都会执行这个方法");
    }
}

``
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值