9

I want to be able to define a parent Controller class which will have a mapping of "/api", and then extend that controller with my different implementations. So ApiController will have:

@Controller
@RequestMapping("/api")

For example, my User controller should extend the base api controller and also add "/users" to the path, so it will answer to "/api/users" requests. So UserController will have:

@Controller
@RequestMapping("/users")

but since it extends ApiController, it will effectively answer to /api/users.

Naturally I can prepend "/api" to all controllers so that this is achieved without the parent class, but I prefer to do it "the right way" if it's possible, so that I can define my api implementations with a cleaner and more visible path.

I tried extending the ApiController base class, but this does not work, UserController still answers to "/users" and ignores the base class "/api".

TheZuck
  • 3,513
  • 2
  • 29
  • 36

2 Answers2

7

Hmmm. You can try this, it is what works for me:

@RequestMapping("/abstract")
public abstract class AbstractController {


}

@Controller
public class ExtendedAbstractController extends AbstractController {

   @RequestMapping("/another")
   public String anotherTest() {
       return "another";
   }

}

Note, your base class must have no @Controller annotation and must be abstract.

If you try to do extend not abstract class annotated as controller and that has @RequestMappings you get errors on step where RequestMappingHandlerMapping initializing.

masted
  • 1,211
  • 2
  • 8
  • 14
  • 1
    Hi, sorry, I must have missed your answer somehow. Unfortunately this will not do what I need, as I want the implementing classes to also have their own "base" mapping, so ExtendedAbstractController should have a @RequestMapping("/another") annotation so that ALL its methods have this prefix. In your solution, only methods with a RequestMapping annotation will have extended annotation. – TheZuck Sep 13 '12 at 06:50
  • 1
    @TheZuck yeah, I see and I know is not what you need. :[ Just was try to help you.:) At the moment Spring does not support inheritance of annotations as you want... Btw you can go to the spring JIRA and vote to same or create new issue with your suggestions. ;) – masted Sep 14 '12 at 10:15
0

You can achieve it with:

  1. create sub-context configuration for controllers with same path prefix
  2. create sub-context with own DispatcherServlet mapped to certain path

Look at this answer. It's similar problem, but for @RestControllers.

Community
  • 1
  • 1
kravemir
  • 10,636
  • 17
  • 64
  • 111