Sharing the parent path when implementing Spring controllers

I want to be able to define the parent class of the controller, which will have a "/ api" mapping, and then extend this controller with different implementation options. 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 respond to requests of "/ api / users". Thus, the UserController will have:

@Controller
@RequestMapping("/users")

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

Naturally, I can add “/ api” to all controllers so that this is achieved without a parent class, but I prefer to do it “correctly” if possible, so that I can define my api implementations using a cleaner and more visible path.

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

+5
source share
2 answers

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

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


}

@Controller
public class ExtendedAbstractController extends AbstractController {

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

}

Please note: your base class should not contain annotations @Controllerand should be abstract .

, , @RequestMapping, , RequestMappingHandlerMapping .

+3

:

  • DispatcherServlet,

. , @RestControllers.

0

All Articles