我尝试使用AOP来包装Http响应。我有以下代码:
@Component
@Aspect
public class ControllerResponse {
@AfterReturning(pointcut = "execution(* hu.example.app.kafkaexample.controller.Controller.*(..))", returning = "entity")
public ResponseEntity<Object> logMethodCall(JoinPoint jp, Object entity) throws Throwable {
System.out.println("Inside of the aop");
ResponseEntity response = new ResponseEntity(entity, HttpStatus.BAD_REQUEST);
return response;
}
}
我可以在控制台上获取日志记录,但 api 调用不受我所做的设置的操纵。我的问题是:我可以通过aop操作响应类型吗?如果是,为什么我的代码不好?
基于 kriegaex 评论,使用
@Around
而不是 @AfterReturning
是允许操纵响应的方法。我尝试过并为我工作。
如果您尝试立即更新标题:
response.getHeaders.add(newHeader)
就我而言,它会导致身份验证错误,并且我会丢失所有响应。所以,这就是我的做法。
顺便说一句,RmsResponseEntity 是我的自定义响应包装器 - 您不需要它。
@Around("@annotation(Session)")
public Object manageSession(ProceedingJoinPoint joinPoint) throws Throwable {
Object returnValue = joinPoint.proceed();
if (returnValue instanceof RmsResponseEntity<?> rmsResponse) {
HttpHeaders updatedHeaders = updateHeaders(rmsResponse.getHeaders());
return new RmsResponseEntity<>(rmsResponse.getBody(), updatedHeaders);
} else if (returnValue instanceof ResponseEntity<?> response) {
HttpHeaders updatedHeaders = updateHeaders(response.getHeaders());
return ResponseEntity.status(response.getStatusCode()).headers(updatedHeaders).body(response.getBody());
}
return returnValue;
}
private HttpHeaders updateHeaders(HttpHeaders httpHeaders) {
String sessionId = UUID.randomUUID().toString();
HttpHeaders updatedHeaders = new HttpHeaders();
updatedHeaders.addAll(httpHeaders);
updatedHeaders.add("Session-Id", sessionId);
return updatedHeaders;
}