2013-10-17 75 views
2

我有一個類A如何在aspectj中將一個方面方法與多個方法關聯?

@Service 
public class A { 
    public void goX() { 
     System.out.println("goX"); 
     try { 
      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 

    public void goY() { 
     System.out.println("goY"); 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

和AOP類AOP

@Aspect 
@Service 
class AOP  { 
    @Around("execution(* com.test.A.goX(..))") 
    public void calExecTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable  { 
     long t1 = System.currentTimeMillis(); 
     proceedingJoinPoint.proceed(); 
     long t2 = System.currentTimeMillis(); 
     System.out.println(t2-t1); 
    } 
} 

然後,我可以算時間A.goX()採用由方法AOP.calExecTime()執行。

我要的是用同樣的方法AOP.calExecTime()來計算兩者A.goX()A.goY()的時候,我不知道怎麼寫東西@Around註解。任何人都可以幫我嗎?非常感謝。

回答

3

這可能有所幫助。

@Aspect 
@Service 
class AOP  { 
@Around("within(* com.test.*)") 
public void calExecTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { 
    long t1 = System.currentTimeMillis(); 
    proceedingJoinPoint.proceed(); 
    long t2 = System.currentTimeMillis(); 
    System.out.println("Method "+ proceedingJoinPoint.getSignature().getName() + " time : "+ t2-t1); 

    } 

    } 
+0

感謝您的回覆!如果'goX'和'goY'屬於不同的類別呢?如果有什麼方法可以在'@ Around'中寫入**和**? – Judking

+0

是的,你可以在(你包。*)內使用,而不是執行。不管你在這個包中有多少個類,你的方法calExecTime都會調用所有的類。但是請確保這不應該造成任何內存問題。我已經在答案中更新了相同的內容。也請在這裏獲得更多關於AOP的信息。 http://docs.spring.io/spring/docs/2.5.x/reference/aop.html –

+0

謝謝bro ~~~~! – Judking