aop注解

Aop注解:
<1>使用注解先导入context命名空间
<?xml version="1.0" encoding="UTF-8"?>

<2>配置spring使其支持aop 注解
在xml文件中添加 aop:aspectj-autoproxy/
<3>配置切面:在通知类的前面加上注解 @Aspect
<4>配置切点 在通知类中添加代码
@PointCut(“execution = ( * .(…))")
private void pt1(){}
注意这里的pt1就是切入点,就相当于xml文件中配置的pointCut 的id=pt1
<5>使用注释注明通知类型
a.前置通知:在通知前面加上备注 @Before(“pt1”) 或者 @before(value = "execution=( * .
(…))”)
b.后置通知:在通知前面加上备注 @AfterReturning(“pt1”) 或者 同上
c.异常通知:在通知前面加上备注 @AfterThrowing(“pt1”) 或者 同上
d.环绕通知:在通知前面加上备注 @ @Around(“pt1()”) 或者 同上

代码:`package Util;

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

/**

  • @author 刘棋军

  • @date2019-02-21
    */
    @Component(“logger”)
    @Aspect
    public class CustomerLogger {

    //切入点配置
    @Pointcut(“execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
    private void pt1(){}

    @Before(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
    public void beforAdvice(){
    System.out.println(“前置通知!”);
    }

    @AfterReturning(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
    public void afterReturn(){
    System.out.println(“后置通知”);
    }

    @After(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
    public void after(){
    System.out.println(“最终通知”);
    }

    @AfterThrowing(value = “execution(* com.liuqijun.spring.CustomerServerImp.update(…))”)
    public void throwing(){
    System.out.println(“异常通知通知”);
    }

    /**

    • spring提供了ProceedingJoinPoint接口:用来做为环绕通知的形参
    • ProceedinngJoinPoint有个proceed方法就相当method.invoke()
    • 环绕通知可以通过手写代码的位置来指定通知类型,之前是在xml文件中配置,在环绕通知中通知与调用切入点的相对位置确定了它的类型
      /
      // @Around(value = "execution(
      com.liuqijun.spring.CustomerServerImp.*(…))")
      public Object around(ProceedingJoinPoint pjp){
      System.out.println(“环绕通知”);
      Object retValue = null;
      //调用切入点
      try {
      System.out.println(“huanrao 前置通知”);
      retValue= pjp.proceed();
      System.out.println(“huanrao 后置通知”);
      } catch (Throwable throwable) {
      throwable.printStackTrace();
      }finally{
      System.out.println(“huanrao 最终通知”);
      }
      return retValue;
      }
      }
      `
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值