为什么不能使用springAOP更改响应类型,除了返回Object



我正在使用Spring AOP来切入我的控制器方法,并试图将公共结构响应返回到前端。定义如下:

public class CommonResponse {
private String status;
private String message;
private Object data;
}

我还有一个点的定义如下:

@Aspect
@Component
public class PostMessageInterceptor {

@Pointcut("within(org.moa.controller.*)")
public void postMessageConvert() {}
@Around("postMessageConvert()")
public CommonResponse modifyResult(ProceedingJoinPoint pjp) {
CommonResponse response = new CommonResponse();
try {
Object result = pjp.proceed();
response.setStatus("success");
response.setData(result);
}catch(Throwable t) {
response.setStatus("failure");
response.setMessage(t.getMessage());
}
return response;
}
}

例如,当控制器中的方法返回类型为Map<String,String>时,在执行modifyResult后,返回类型已从Map<String,String>转换为CommonResponse,则Spring AOP将发生异常java.lang.ClassCastException: CommonResponse cannot be cast to java.util.Map

如果我将此方法的返回类型更改为Object,它将正常工作。

我只想这样设计吗?否则,有没有任何方法可以在不将返回类型修改为Object的情况下实现这个目标。因为感觉很奇怪,所有方法都返回相同类型的Object。

您不能更改被包围方法的返回类型。JVM的机制不允许这样(请参阅这个问题的答案(。

方法的调用方根据原始方法的接口编译代码,但在执行设备后,方法返回不同的类型。这应该如何运作?

一种可能性是使用一个接口并返回一个不同的实现,由您的建议创建,例如:

interface MyReturnType {
int getStatus();
Map<String, String> getData();
}
class MethodReturnType implements MyReturnType {
int getStatus() { throw NotImplementedException(); } 
// should never be called; every other method in the interface can be implemented in the exact same way

Map<String, String> getData() { return data; } // I omit the constructor and field decleration here
}
class AdviceReturnType implements MyReturnType {
int status;
Map<String, String> data;
int getStatus() { return status; } 
Map<String, String> getData() { return data; }
}

public MyReturnType myAdvicedMethod(...) {
// ...
return new MethodReturnType(myCalculatedData);
}
public Object aroundAdvice(ProceedingJoinPoint pjp) {
MyReturnType retVal = (MyReturnType) pjp.proceed();
// calculate status and stuff
return new AdviceReturnType(retVal.getData(), caluclatedStatus, ...);
}

最新更新