You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC中子类继承父类时能否调用父类@RequestMapping路径?

我来帮你理清楚这个Spring MVC控制器继承的问题哈,先拆解下你的疑问和报错原因,再给出可行的解决方案:

问题根源分析

  1. 为什么/parent/hello访问报错?
    你的父类Parent是抽象类——哪怕你给它加了@Controller,Spring也不会创建抽象类的实例对象,所以父类上的@RequestMapping("/parent")根本不会被Spring MVC注册成独立的请求映射。直接访问/parent/hello自然找不到对应的处理器,就会抛出那个警告。

  2. 父类的@RequestMapping方法能不能被访问?
    当然可以,但得通过子类的请求路径来访问。因为你的子类Child标记了@Controller,Spring会实例化它,并且自动扫描子类及其父类中所有公开的@RequestMapping方法。此时父类的world()方法会和子类的类级别@RequestMapping("/child")组合,生成有效映射路径/child/hello。

针对不同需求的解决方案

需求1:只想通过子类访问父类的方法

这种情况最简单,不需要给父类加@Controller,保持它的抽象类状态就行。你只需要修正页面上的链接:

  • 把<a href="parent/hello">BaseHello</a>改成<a href="child/hello">BaseHello(通过子类访问)</a>
  • 确保子类Child的@Controller注解存在,这样点击新的链接就能正确触发父类的world()方法,返回hellopage了。

需求2:希望同时支持/parent/hello和/child/hello两个路径

有两种靠谱的实现方式:

  • 方式一:让父类成为独立的控制器
    去掉父类的abstract修饰符,加上@Controller注解:

    @Controller
    @RequestMapping("/parent")
    public class Parent {
        @RequestMapping("/hello")
        public String world() {
            return "hellopage";
        }
    }
    

    这样Spring会同时创建Parent和Child的实例,两个路径/parent/hello和/child/hello都能正常访问。

  • 方式二:子类继承父类并配置多路径映射
    父类继续保持抽象类,在子类的@RequestMapping里同时指定父类和子类的路径:

    @Controller
    @RequestMapping({"/child", "/parent"})
    public class Child extends Parent {
        @RequestMapping("/detail")
        public String info() {
            return "detailpage";
        }
    }
    

    这时候子类继承的world()方法会同时映射到/child/hello和/parent/hello,而子类自己的info()方法也会同时对应/child/detail和/parent/detail。

额外要注意的小细节

  • 父类中被继承的@RequestMapping方法必须是public的,Spring MVC不会处理私有或受保护的继承方法。
  • 如果父类和子类有路径完全相同的@RequestMapping方法,子类的方法会覆盖父类的实现。

内容的提问来源于stack exchange,提问作者Harry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:22:37