Programmatically call @Controller

java, spring, spring-mvc

Solution

You just call the method on the object. That's one of the big benefits of annotation-driven controllers, you can write just the methods your code needs without having to bend things out of shape to conform to the interfaces. So just wire your controller bean into your code, and call the method directly.

Or are you saying you want to re-invent the mechanism by which Spring maps requests on to annotated-controllers? If so, have a look at the source for Spring's `AnnotationMethodHandlerAdapter` and `DefaultAnnotationHandlerMapping` classes. It's complex, though - annotated controllers make it easier to write controllers, but the underlying mechanism is unpleasant.

Problem

I am transitioning code that used implementations of Spring MVC's Controller to use the annotation stereotype @Controller. Everything is going fine except for one issue: Given a request/response, how do I programmatically handle requests for annotation-based controllers? Previously, (regardless of implementation) I was able to call: ``` controller.handleRequest(request, response) ``` What is the equivalent with annotations? I had assumed there would be some (perhaps static?) utility class along the lines of: ``` SpringAnnotationBasedControllerUtils.handleRequest(<? extends @Controller> handlerObject, HttpServletRequest request, HttpServletResponse response); ``` to handle the details of mapping a request to the dynamic signatures allowed by the @Controller stereotype, but I can't find such a thing. Any suggestions? (Please no comments on why this is a bad idea or should be unnecessary with a "good" design, etc. This is code under maintenance and must be as noninvasive as possible so a complete re-write is not an option at this time.) Thanks!

Original source