SpringBoot @RequestMapping 继承冲突解决方法 - 避免父类注解覆盖
在使用 Spring Boot 的 @RequestMapping 注解时,如果子类和父类都使用了该注解,则可能会出现继承冲突的情况。
解决方法之一是在子类的 @RequestMapping 注解中指定 path 属性,覆盖父类的注解。如下所示:
@RestController
@RequestMapping("/parent")
public class ParentController {
@GetMapping("/hello")
public String hello() {
return "Hello from parent";
}
}
@RestController
@RequestMapping("/child")
public class ChildController extends ParentController {
@GetMapping(path = "/hello")
public String hello() {
return "Hello from child";
}
}
在这个例子中,父类和子类都有一个 @GetMapping("/hello") 的注解,但是子类使用了 path 属性来覆盖父类的注解,所以访问 "/child/hello" 时会返回 "Hello from child"。
另一种解决方法是在父类的 @RequestMapping 注解中使用 abstract 属性,使其不被继承。如下所示:
@RestController
@RequestMapping(path = "/parent", abstract = true)
public abstract class ParentController {
@GetMapping("/hello")
public String hello() {
return "Hello from parent";
}
}
@RestController
@RequestMapping("/child")
public class ChildController extends ParentController {
@GetMapping("/hello")
public String hello() {
return "Hello from child";
}
}
在这个例子中,父类的 @RequestMapping 注解中使用了 abstract 属性,所以子类不会继承父类的 @RequestMapping 注解。因此,访问 "/child/hello" 时也会返回 "Hello from child"。
原文地址: https://www.cveoy.top/t/topic/oiOi 著作权归作者所有。请勿转载和采集!