使用spring,aspectj和annotation

时间:2015-07-10 09:32:52

标签: spring annotations aop aspectj

我有一个关于如何使用注释,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时没有为该方法触发方面。 我做错了什么?

1 个答案:

答案 0 :(得分:0)

总结一个简短的教程,如何与Annotation一起创建一个方面,对这个领域的新人有用。

  1. 您需要库依赖项: aspectjrt aspectjweaver 春天的AOP 以及其他弹簧依赖关系,如春天上下文等。
  2. 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. 确保您的春季上下文正在扫描您拥有Aspect的包,以及您在其中注释类的包。或者您可以在spring上下文配置中将它们声明为bean。

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

         <?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 />
      
    3. 就是这样。 我希望它对某人有用。