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

将Controller拆分至接口与实现后,调用Web应用为何返回404?

问题原因及解决方法

核心原因是Spring MVC默认不会解析接口上的@RequestMapping衍生注解(如@GetMapping),即使实现类标注了@RestController,接口上的路由配置也不会被Spring的请求映射处理器识别。

具体原因

  • Spring的请求映射扫描逻辑仅针对类和方法本身的注解,不会读取接口上的请求路由注解。你把@GetMapping放在了ProductService接口上,实现类ProductServiceImpl只是实现了接口方法,但并没有继承接口上的路由注解,导致Spring找不到对应路径的请求处理方法,返回404错误。

解决方法

方案一(推荐):将路由注解移到实现类方法上

把接口上的@GetMapping注解迁移到实现类的对应方法上,保持实现类的@RestController注解即可:

// 接口定义
public interface ProductService {
    Product getProductById(Long productId);
}

// 实现类
@RestController
public class ProductServiceImpl implements ProductService {

    @Override
    @GetMapping("/product/{productId}")
    public Product getProductById(@PathVariable("productId") Long productId) {
        // 业务逻辑实现
        return new Product();
    }
}

方案二(不推荐):开启接口注解继承支持

如果一定要保留接口上的路由注解,需要自定义配置开启Spring对接口注解的解析,在配置类中设置RequestMappingHandlerMapping的属性:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping handlerMapping = new RequestMappingHandlerMapping();
        // 允许从父类/接口中检测请求处理方法
        handlerMapping.setDetectHandlerMethodsInAncestorContexts(true);
        return handlerMapping;
    }
}

这种方式会增加项目复杂度,且不符合Spring MVC的常规开发实践,一般不建议使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 02:52:13