简体   繁体   English

Spring MVC(Spring Boot)——RequestMapping继承

[英]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.我正在寻找的是一种扩展ControllerRequestMapping注释值的好方法。

Such as:如:

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

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

The result should be ("/api/dashboard") .结果应该是("/api/dashboard")

This approach apparently simply override the RequestMapping value.这种方法显然只是覆盖了RequestMapping值。 A working approach may be to not put a RequestMapping annotation on the derived class.一种可行的方法可能是不在派生类上放置 RequestMapping 注释。

@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".在这种情况下,它将是“/api/dashboard”。

Values for the exact same parameter override on subclasses, they don't accumulate子类上完全相同的参数覆盖的值,它们不会累积

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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