简体   繁体   中英

Spring MVC (Spring Boot) - RequestMapping inheritance

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.

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 {}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM