3

Edit: please read the question curefully, I don't need answers that repeat what I wrote.

Looking aroung the web I found quite a confusion about this subject. What I'm looking for is a nice way to extend the value of a Controller's RequestMapping annotation.

Such as:

@Controller
@RequestMapping("/api")
public class ApiController {}

@Controller
@RequestMapping("/dashboard")
public class DashboardApiController extends ApiController {}

The result should be ("/api/dashboard").

This approach apparently simply override the RequestMapping value. A working approach may be to not put a RequestMapping annotation on the derived class.

@Controller
public class DashboardApiController extends ApiController
{
   @GetMapping("/dashboard")
   public String dashboardHome() {
      return "dashboard";
   }

   ... other methods prefixed with "/dashboard"
}

Is this the only feasible approach? I don't really like it.

LppEdd
  • 20,274
  • 11
  • 84
  • 139
  • 1
    this question already exists... https://stackoverflow.com/q/5268643/2736849 – mfaisalhyder Oct 26 '17 at 13:27
  • 3
    Possible duplicate of [Spring MVC @RequestMapping Inheritance](https://stackoverflow.com/questions/5268643/spring-mvc-requestmapping-inheritance) – g00glen00b Oct 26 '17 at 13:28
  • @MuhammadFaisalHyder I know. We now have newer releases of Spring MVC and Spring Boot, but the documentation is a bit ctyptical as it has always been. Also, someone may have come up with a nice trick to solve this problem – LppEdd Oct 26 '17 at 13:29
  • Maybe have a look at this GitHub issue: https://github.com/spring-projects/spring-framework/issues/16048 – Flimtix Jun 01 '22 at 12:22

3 Answers3

3

This is not the elegant solution you're looking for, but here's a functional solution I used.

@Controller
@RequestMapping(BASE_URI)
public class ApiController {
   protected final static String BASE_URI = "/api";
}

@Controller
@RequestMapping(ApiController.BASE_URI + "/dashboard")
public class DashboardApiController extends ApiController {}
rdChris
  • 96
  • 4
0

Values get overridden in the subclasses and not appended. You would need to specify the full path in the child class.

Arpit
  • 323
  • 4
  • 13
-1

You can achieve what you are trying to by adding

@Controller
@RequestMapping("/api")
public class DashboardApiController extends WhateverClassWithWhateverMapping
{
   @RequestMapping("/dashboard")
   public String dashboardHome() {
      return "dashboard";
   }

}

In this case it will be "/api/dashboard".

Values for the exact same parameter override on subclasses, they don't accumulate

shakeel
  • 1,609
  • 1
  • 14
  • 14
  • this doesn't answer the initial question. `WhateverClassWithWhateverMapping` is useless in your situation but in the question it's the key for the answer – Sîrbu Nicolae-Cezar Sep 25 '18 at 17:42