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

SpringBoot启动类添加@RequestMapping作为全局API前缀是否可行?

解决SpringBoot全局API前缀配置问题

你的问题出在启动类不能通过添加@RestController和@RequestMapping来设置全局前缀,启动类的核心作用是引导SpringBoot应用启动,并非处理请求的控制器,所以这种配置不会生效,反而会导致路径匹配异常。

下面是几种正确实现全局API前缀的方式:

方法一:通过配置文件快速设置

这是最简洁的实现方式,直接在配置文件中定义全局前缀:

  • 若使用application.properties:
spring.mvc.servlet.path=/api/v1
  • 若使用application.yml:
spring:
  mvc:
    servlet:
      path: /api/v1

配置完成后,你的ProductController可以这样编写:

@RestController
@RequestMapping("/products")
public class ProductController {
    @GetMapping("")
    public String getProducts() {
        return "产品列表";
    }
}

此时访问/api/v1/products即可正常返回结果。

方法二:通过WebMvcConfigurer自定义配置

如果需要更灵活的规则(比如仅给特定注解的控制器添加前缀),可以实现WebMvcConfigurer接口:

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // 给所有标注@RestController的控制器自动添加/api/v1前缀
        configurer.addPathPrefix("/api/v1", c -> c.isAnnotationPresent(RestController.class));
    }
}

ProductController的写法与方法一保持一致即可。

纠正启动类的错误写法

请移除启动类上的@RestController和@RequestMapping,启动类仅保留核心注解:

@SpringBootApplication
public class CommonApplication {
    public static void main(String[] args) {
        SpringApplication.run(CommonApplication.class, args);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 00:55:33