问题描述
我正在尝试将AspectJ用于授权和请求响应日志记录。但是问题在于它正在打开两个线程。两次执行我的控制器和服务方法。任何帮助都会得到应用。
@Around("execution(* com.a.b.c.controller.*.*(..)) && @annotation(com.a.b.c.role.auth.ReadAuthorization) && args(request,obj)")
public Object before(ProceedingJoinPoint joinPoint,HttpServletRequest request,Object obj) throws Throwable {
Object result = null;
if (!(request instanceof HttpServletRequest)) {
throw new RuntimeException("You are not authorized");
}
LoggingObject loggingObject = new LoggingObject();
loggingObject.setMethodName(MethodSignature.class.cast(joinPoint.getSignature()).getMethod().getName());
loggingObject.setRequestObject(obj);
try{
Object requestObject = joinPoint.proceed();
loggingObject.setResponseObject(requestObject);
log.info(mapperObj.writeValueAsString(loggingObject));
}catch(Exception e){
loggingObject.setResponseObject(e);
log.info(mapperObj.writeValueAsString(loggingObject));
}
if (auth.authorize(request.getHeader("id"),request.getHeader("token"))) {
result = joinPoint.proceed();
return result;
} else {
throw new RuntimeException("You are not authorized");
}
}
解决方法
即使您在谈论线程时仍不清楚该问题,我也冒着有根据的猜测的风险(请参阅评论中有关如何改进问题的问题):
您可能的意思是简单地将目标方法执行两次,而不是方面创建了两个线程,对吗?好吧,您的 advice方法包含两个ac9edf2
调用。如果您两次调用目标方法,为什么会对目标方法执行两次感到惊讶呢?
我认为应该可以回答您的问题。