2017-05-26 108 views
0

問題是@Before和@AfterReturning正在工作,但Pointcut並非如此。未觸發彈簧aop切入點

這是我的方面。

作爲springboot服務的一部分,我想要做的就是用第一種方法profile觸發切入點來顯示執行時間和其他事情。

我錯過了什麼嗎?

package com.myproj.service.myagg.aop; 

import org.aspectj.lang.JoinPoint; 
import org.aspectj.lang.ProceedingJoinPoint; 
import org.aspectj.lang.annotation.AfterReturning; 
import org.aspectj.lang.annotation.Aspect; 
import org.aspectj.lang.annotation.Before; 
import org.aspectj.lang.annotation.Pointcut; 
import org.springframework.stereotype.Component; 
import org.springframework.util.StopWatch; 

/** 
* Created by shammami on 26/05/2017. 
*/ 
@Aspect 
@Component 
public class LoggingService { 

    @Pointcut("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))") 
    public Object profile(ProceedingJoinPoint pjp) throws Throwable { 
     StopWatch stopWatch = new StopWatch(); 
     stopWatch.start(); 
     boolean isExceptionThrown = false; 
     try { 
      // execute the profiled method 
      return pjp.proceed(); 
     } catch (RuntimeException e) { 
      isExceptionThrown = true; 
      throw e; 
     } finally { 
      stopWatch.stop(); 
      StopWatch.TaskInfo taskInfo = stopWatch.getLastTaskInfo(); 
      // Log the method's profiling result 
      String profileMessage = taskInfo.getTaskName() + ": " + taskInfo.getTimeMillis() + " ms" + 
        (isExceptionThrown ? " (thrown Exception)" : ""); 
      System.out.println(profileMessage); 
     } 
    } 

    @Before("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))") 
    public void before(JoinPoint joinPoint) { 
     System.out.println("Started: " + joinPoint.getStaticPart().getSignature().toLongString()); 
    } 

    @AfterReturning("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))") 
    public void completed(JoinPoint joinPoint) { 
     System.out.println("Completed: " + joinPoint.getStaticPart().getSignature().toLongString()); 
    } 
} 

回答

0

當你用註釋@Pointcut 基本上定義切入點簽名的東西,你不能做有什麼樣的處理。你需要做的是創建另一個具有所有處理細節的方法,並使用上面評估的切入點簽名。因此,

@Pointcut("execution(public void com.myproj.service.myagg.listener.MyMessageConsumer.handleMessage(..))") 
public void myPointcutSignature(){ 
//This basically has nothing :) 
} 

@Around("myPointcutSignature") 
public Object profile(ProceedingJoinPoint pjp) throws Throwable { 
    StopWatch stopWatch = new StopWatch(); 
    stopWatch.start(); 
    boolean isExceptionThrown = false; 
    //And the remaining code 
    ------- 
} 

希望這項工程。另外請記住,ProceedingJoinPoint只能用於@Around建議。

+0

非常感謝!它現在有效! – Sofiane