2015-07-10 35 views
0

我有一個關於如何通過使用註釋的方法做了一次績效審計問題,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。 我做錯了什麼?

+0

[Perf4J](http://www.infoq.com/articles/perf4j)。 – manish

+0

謝謝你,它似乎做那個表現測量。但我想看看我能做到這一點。 – DanutClapa

+0

您可以查看[Perf4J源代碼](https://github.com/perf4j/perf4j)。 '@ Profiled'註釋位於'aop'包中。這會觸發同樣包中的'ProfiledTimingAspect'。從這裏您可以按照代碼來了解實際測量和記錄的處理方式。 AspectJ配置在我鏈接到上面的頁面上。 – manish

回答

0

總結一個簡短的教程,如何創建一個與註釋相結合的方面,以便對這個領域的新手有用。

  1. 您需要的庫的依賴: aspectjrt aspectjweaver 彈簧AOP 與人相處春天像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在你的方法中使用你的註解就像這樣 - 一點點的觀察就是你可以創建Annotation來按你的意願行事。

@Repository 
public class MyClass{ 
@Override 
@TimeAudit 
public void myMethod(){ 
    //do something 
} 
} 
//- this @TimeAudit can contain params, this depends on your Annotation logic creation 
  • 確保您的Spring上下文正在掃描你的包,你有看點,而且,你必須在類註釋的包。或者你可以在spring上下文配置中將它們聲明爲bean。

  • 確保啓用了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 /> 
    
  • 就是這樣。 我希望它對某人有用。