问题是@Before和@AfterReturning正在运作,但Pointcut并非如此。
这是我的方面。
作为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 :(得分: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建议。