Spring Boot 2.0.2如何配置默认带/api前缀的重置接口无需显式指定?
解决方案:Spring Boot 2.0.2 给重置服务自动添加/api前缀
针对你想让重置服务请求默认带上/api前缀,无需在每个URL映射中显式指定的需求,结合Spring Boot 2.0.2的版本特性,这里提供几种实用方案:
方案一:通过父类控制器精准控制(推荐仅重置服务需要前缀的场景)
这种方式只给重置服务的控制器添加前缀,不会影响其他接口,实现起来也很简单:
- 创建一个带
/api前缀的父类控制器:
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; // 统一添加/api前缀 @RequestMapping("/api") @RestController public abstract class BaseResetApiController { }
- 让你的重置服务控制器继承这个父类:
public class ResetController extends BaseResetApiController { // 这里只需写具体的路径,无需加/api @GetMapping("/defaultuser") public ResponseEntity<Void> resetDefaultUser() { // 你的重置业务逻辑 return ResponseEntity.ok().build(); } }
这样配置后,访问重置接口的实际路径就是http://localhost:9080/DTHMS/api/defaultuser,完全符合你的需求。
方案二:通过@ControllerAdvice给指定包下的接口加前缀
如果你的重置服务相关控制器都集中在同一个包下,可以用这种方式批量添加前缀:
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.RequestMapping; // 指定重置服务所在的包路径 @ControllerAdvice(basePackages = "com.yourproject.controller.reset") @RequestMapping("/api") public class ResetApiPrefixConfig { }
这个配置会让指定包下的所有控制器的请求映射自动带上/api前缀,其他包的接口不受影响。
方案三:全局添加/api前缀(适合所有接口都需要该前缀的场景)
如果你希望整个应用的所有接口都默认带上/api前缀,可以通过自定义RequestMappingHandlerMapping实现:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; @Configuration public class WebMvcConfig { @Bean public RequestMappingHandlerMapping requestMappingHandlerMapping() { RequestMappingHandlerMapping mapping = new RequestMappingHandlerMapping(); // 设置全局路径前缀 mapping.setPrefix("/api"); // 可选:关闭后缀匹配,避免类似 .json 的后缀干扰路径匹配 mapping.setUseSuffixPatternMatch(false); return mapping; } }
注意事项
由于你使用的是Spring Boot 2.0.2,对应的Spring版本是5.0.x,而WebMvcConfigurer的addPathPrefix方法是Spring 5.1才引入的,所以这个方法在你的版本中不可用,上面的三种方案都是适配2.0.2版本的可行方案。
内容的提问来源于stack exchange,提问作者Premkumar Pallinti
相关产品推荐
相关产品推荐

