基于spring@aspect注解的aop实现过程代码实例

@AspectJ 作为通过 Java 5 注释注释的普通的 Java 类,它指的是声明 aspects 的一种风格。通过在你的基于架构的 XML 配置文件中包含以下元素,@AspectJ 支持是可用的。

第一步:编写切面类

package com.dascom.hawk.app.web.tool;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AnnotationAspectJ {

  //定义切面("execution(* com.dascom.common.aop.*.*(..)))
  //当前配置的意思是所有添加了SuiteMessage的注解的方法作为切点
  @Pointcut("@annotation(com.dascom.common.annotation.SuiteMessage)")
  public void logPointCut() {
  }
  
  //前置通知
  @Before("logPointCut()")
  public void before(JoinPoint point) {
    String calssName = point.getTarget().getClass().getName();
    String method = point.getSignature().getName();
    System.out.println(calssName + " : " + method);
  }
  
  //后置通知
  @After("logPointCut()")
  public void after(JoinPoint point) {
    String method = point.getSignature().getName();
    System.out.println(method + ": end----");
  }
  
  //环绕通知
  @Around("logPointCut()")
  public Object around(ProceedingJoinPoint point) throws Throwable {
    long beginTime = System.currentTimeMillis();
    // 执行方法
    Object result = point.proceed();
    // 执行时长(毫秒)
    long time = System.currentTimeMillis() - beginTime;
    //异步保存日志
    System.out.println(time);
    return result;
  }
}

第二步:在spring的配置文件中添加注解扫描



  
  
  
  
  

第三步:搞定。爽歪歪~~~

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(基于spring@aspect注解的aop实现过程代码实例)