【问题标题】:Performance method audit with spring, aspectj and annotation based基于 spring、aspectj 和注释的性能方法审计
【发布时间】:2015-07-13 16:43:43
【问题描述】:

我有一个关于如何使用注释、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;
}
}

在其他课程上:

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

但是如果我设置了@TimeAudit,则不会为该方法触发方面。 我做错了什么?

【问题讨论】:

标签: spring annotations aop aspectj


【解决方案1】:

总结一个简短的教程,如何结合 Annotation 创建一个方面,以便对这个领域的新手有用。

  1. 您需要库依赖项: 方面jrt 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 的包,以及你有注释的类的包。或者您可以在 Spring 上下文配置中将它们声明为 bean。

  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 />
    

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2015-03-25
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多