美文网首页spring
spring aop 常用注解

spring aop 常用注解

作者: empathy_145d | 来源:发表于2020-03-02 18:26 被阅读0次
注解 简述
@EnableAspectJAutoProxy 开启注解切面
@Aspect 标识当前类为切面类
@Pointcut 切入点, 符合规则的类才会生成代理对象
@Before 前置增强
@Around 环绕增强,调用被代理对象方法需要自行控制
@After 后置增强,不管是抛出异常或者正常退出都会执行
@AfterReturning 后置增强,异常不执行
@AfterThrowing 后置增强,抛出异常时执行
@EnableAspectJAutoProxy 属性 proxyTargetClass

true 使用CGLIB代理机制

false 

  1、目标对象实现了接口 – 使用JDK动态代理机制

  2、目标对象没有接口(只有实现类) – 使用CGLIB代理机制

使用案例

@Component

@Aspect

public class AspectAnnotation {

  /*

  * introduction 引介动态添加功能,并且改变目标类的类型,其实就是目标类多实现了接口而已

  * */

  @DeclareParents(value = "com.xiangxue.jack.service1.BankServiceImpl",

          defaultImpl = com.xiangxue.jack.service.DataCheckImpl.class)

  private DataCheck dataCheck;

  @Pointcut("execution(public * com.xiangxue.jack.service.*.*(..))")

  public void pc1(){}

  @Pointcut("execution(public * com.xiangxue.jack.service.*.add*(..))")

  public void pc2(){}

  @Pointcut("execution(public * com.xiangxue.jack.service1.*.*(..))")

  public void pc3(){}

  @Before("pc2()")

  public void before() {

      System.out.println("===============只拦截add方法=========");

  }

  @Around("pc1()")

  public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

      System.out.println("==============AspectAnnotation around前置通知=========");

      Object result = joinPoint.proceed();

      System.out.println("==============AspectAnnotation around后置通知=========");

      return result;

  }

  @Before("pc3()")

  public void before1(JoinPoint joinPoint) {

      Signature signature = joinPoint.getSignature();

      Object[] args = joinPoint.getArgs();

      System.out.println("===============service1包的拦截=========");

  }

  @Before("pc3()&&args(bankId,id,list)")

  public void before2(String bankId,Integer id,List list) {

      System.out.println("===============service1包的拦截=========");

  }

  @Before(value = "@annotation(targetMethod)",argNames = "joinPoint,targetMethod")

  public void xx(JoinPoint joinPoint, TargetMethod targetMethod) {

      System.out.println("===============注解拦截 前置通知=========");

      System.out.println("==================targetMethod.name = " + targetMethod.name());

  }

  @AfterReturning(value = "@annotation(returnValue)",returning = "retVal")

  public void afterReturning(JoinPoint joinPoint, ReturnValue returnValue, Object retVal) {

      System.out.println("==============AspectAnnotation 后置通知  拿返回值=========" + retVal);

  }

  @AfterThrowing(value = "@annotation(throwsAnno)",throwing = "e")

  public void throwMethod(JoinPoint joinPoint, ThrowsAnno throwsAnno, Throwable e) {

      System.out.println("==============AspectAnnotation 异常通知  拿异常=========" + e);

  }

}

相关文章

网友评论

    本文标题:spring aop 常用注解

    本文链接:https://www.haomeiwen.com/subject/fokbkhtx.html