Skip to content
Advertisement

Choose Controller Bean instance by RequestMapping

I want Spring to create 2 instances of FooController. Requests to /foo should be handled by one of the instances and requests to /bar should be handled by the other instance. I want something like the below, but of course @RequestMapping doesn’t work that way and also Spring gives me the ambiguous mapping error on FooController as well.

JavaScript

Advertisement

Answer

Don’t try this at home. This code was performed by a bored, trained professional…

You can have multiple instances of the same controller class, each of which handles a different URL through the same or a different method in the controller. The only thing is, I don’t know how to do it with just annotations. The way I just did it was to dynamically register each request mapping at initialization time. The FooController becomes a prototype bean (defined with annotations) so you can have Spring instantiate it multiple times, once for each mapping

FooController.java

JavaScript

EndpointService.java

JavaScript

Results:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement