Spring AOP(2)

目录

Spring AOP详解

@PointCut

切面优先级@Order

切点表达式

execution表达式

切点表达式示例

@annotation

 自定义注解@MyAspect

 切面类

添加自定义注解


Spring AOP详解

@PointCut

上面代码存在一个问题, 就是对于excution(* com.example.demo.controller.*.*(..))的大量重复使用, Spring提供了@PointCut注解, 把公共的切点表达式提取出来, 需要用到时引入切点表达式即可.

@Slf4j
@Component
@Aspect
public class AspectDemo {
    //声明一个切点
    @Pointcut("execution(* com.bite.aop.controller.*.*(..))")
    public void pt(){}; //切点名称:pt()

    @Before("pt()")
    public void doBefore() {
        //此处省略...
    }

    @After("pt()")
    public void doAfter() {
        //此处省略...
    }

    @Around("pt()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        //此处省略...
    }

    @AfterReturning("pt()")
    public void doAfterReturning() {
        //此处省略...
    }
}

 当切点定义为private修饰时, 仅能在当前切面类使用, 当其他切面类也要使用当前切点定义时, 就需要把private改为public. 引用方式为: 全限定类名.方法名()

使用示例:

@Slf4j
@Aspect
@Component
public class AspectDemo2 {
    //前置通知
    @Before("com.example.demo.aspect.AspectDemo.pt()")
    public void doBefore() {
        log.info("卢本伟牛逼");
    }
}

切面优先级@Order

当我们在一个项目中, 定义了多个切面类时, 并且这些切面类的多个切入点都匹配到了同一个目标方法. 当目标方法运行的时候, 这些切面类中的通知方法都会执行, 那么这些通知方法的执行顺序是怎样的呢?

还是通过程序求证:

定义多个切面类如下:

@Component
public class AspectDemo2 {
    @Pointcut("execution(* com.example.demo.controller.*.*(..))")
    private void pt(){}
    //前置通知
    @Before("pt()")
    public void doBefore() {
        log.info("执⾏ AspectDemo2 -> Before ⽅法");
    }
    //后置通知
    @After("pt()")
    public void doAfter() {
        log.info("执⾏ AspectDemo2 -> After ⽅法");
    }
}

@Component
public class AspectDemo3 {
    @Pointcut("execution(* com.example.demo.controller.*.*(..))")
    private void pt(){}
    //前置通知
    @Before("pt()")
    public void doBefore() {
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值