Change return type with AspectJ spring -aop

I want to execute a JSON response received from adding a controller. status attribute. In this regard, I am going to use the Aspect class, which the @Around method returns a custom class object. In this case, I get an error:

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

Is there a way to change the return of type @ResponseBody to a custom type through aspectJ @Around annotation? I can’t change the controller code!

Controller Class:

 @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(); } ... } 

Aspect Class:

 @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; } } 

Custom RestResponse Class:

 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 } 
+6
source share
2 answers

ClassCastException is the normal situation in this case. Look at the answer to this closed question .

So, I think you should find another solution. I have a similar problem

+2
source

I think there is some problem with your point reduction. If you want the point to be truncated by the get () method of the controller class, you should have used something like this:

 @Pointcut("execution(* package..Controller.get(..))") . 

In your case, you can simply check to see if the dot reduction applied by you applies to the get () method of the Controller class or to any other method in the controller.api package. * by debugging the stream.

Hope this solves your problem.

0
source

Source: https://habr.com/ru/post/973014/


All Articles