基于 spring、aspectj 和注释的性能方法审计

Performance method audit with spring, aspectj and annotation based

我有一个关于如何使用注释、aspectj 和 spring

对方法进行时间性能审计的问题

基本上我有:

 public class MyClass{

 @TimeAudit
 public myMethod(){
  //do something
 }
}

我只想在某个地方记录(或只是在控制台中打印)执行该方法所花费的时间。我的问题是一个方面将如何拦截该注释,然后计算该方法花费的时间。

我该怎么做? 澄清一点我的问题: 我有注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface TimeAudit {

}

我有我的一面:

@Aspect
@Component
public class PerformanceTimeExecutionAudit {

     @Around("execution(* *(..)) && @annotation(timeAudit)")
     public Object doLogTime(final ProceedingJoinPoint pjp, TimeAudit timeAudit) throws Throwable {

    System.out.println("Start time..."+System.currentTimeMillis());
    Object output = pjp.proceed();
    System.out.println("End time..."+System.currentTimeMillis());

    return output;
}
}

其他 class:

 @Repository
 public class MyClass{ 
 @Override
 @TimeAudit
  public void myMethod(){
    //do something
   }
 }

但是我放置@TimeAudit 时不会为该方法触发方面。 我做错了什么?

总结一个简短的教程,介绍如何结合 Annotation 创建方面,以供该领域的新手使用。

  1. 您需要库依赖项: 方面 aspectjweaver spring-aop 以及其他 spring 依赖项,例如 spring 上下文等

2 创建注释示例:

 @Retention(RetentionPolicy.RUNTIME)
 @Target({ElementType.METHOD, ElementType.TYPE})
 public @interface TimeAudit {
  //put here whatever fields you need
 }

3 创建你的方面,例如:

@Aspect
@Component
public class PerformanceTimeExecutionAudit {

 @Around("execution(* *(..)) && @annotation(TimeAudit)")
 public Object doLogTime(final ProceedingJoinPoint pjp, TimeAudit timeAudit) throws Throwable {

   System.out.println("Start time..."+System.currentTimeMillis());
   Object output = pjp.proceed();
    //this is with @Around, you can use in your asspect all others annotations like @Before, @After etc. this depends on your logic behavior.
   System.out.println("End time..."+System.currentTimeMillis());

   return output;
 }
}

4 在您的方法上,像这样使用您的注释 - 一点观察是您可以创建注释以按您想要的方式运行。

@Repository
public class MyClass{ 
 @Override
 @TimeAudit 
 public void myMethod(){
   //do something
 }
} 
//- this @TimeAudit can contain params, this depends on your Annotation  logic creation
  1. 请确保您的 spring 上下文正在扫描您拥有 Aspect 的包,以及您具有 class 注释的包。或者您可以在 spring 上下文配置中将它们声明为 beans。

  2. 确保您启用了 AOP。您的 spring 配置中需要这样的东西:

       <?xml version="1.0" encoding="UTF-8"?>
       <beans xmlns="........
        xmlns:aop="http://www.springframework.org/schema/aop"
        xsi:schemaLocation=".........
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
     <aop:aspectj-autoproxy />
    

就是这样。 我希望它对某人有用。