在使用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"

springboot requestMapping 继承冲突

原文地址: https://www.cveoy.top/t/topic/fy0e 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录