gpt4 book ai didi

java - 使用 AspectJ spring-aop 改变返回值的类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:33 24 4
gpt4 key购买 nike

<分区>

我想完成从 Controller 收到的 JSON 响应,添加例如状态属性。在这方面,我将使用 Aspect 类,它的 @Around 方法返回一个自定义类对象。在这种情况下,我得到一个错误:

java.lang.ClassCastException: *.controller.RestResponse cannot be cast to java.util.List

有没有办法通过aspectJ 注解@Around 将@ResponseBody 类型的返回更改为自定义类型?我无法更改 Controller 代码!

Controller 类:

@Controller
@RequestMapping(value = "/users")
public class UserController {

@Autowired
private UserService userService;

@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public List<User> get() throws InterruptedException {
return userService.getUsers();
}
...
}

方面类:

@Component
@Aspect
public class RestInterceptor {

@Pointcut("within(* controller.api.*)")
public void endpointMethod() {
}

@Around("endpointMethod()")
public RestResponse unifyResponse(ProceedingJoinPoint pjp) throws Throwable {
Object controllerResult = pjp.proceed();
RestResponse result = new RestResponse(0, controllerResult);
return result;
}
}

自定义类 RestResponse:

public class RestResponse{

private int status;
private String message;
private Object data;

public RestResponse(int status, Object data) {
this.status = status;
this.data = data;
}

public RestResponse(int status, String message) {
this.status = status;
this.message = message;
}
//getters and setters
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com