Spring Boot 2.2.4如何给接口添加/api前缀且排除静态资源路径
Spring Boot 仅为API接口统一添加/api前缀方案
你之前通过修改DispatcherServlet映射路径的方案会把所有请求(包括静态资源、页面请求)都加上/api前缀,不符合你的需求,推荐使用如下更精准的路径前缀配置方案:
注意:请先删除你之前配置的
DispatcherServletCustomConfiguration类,避免出现路径映射冲突。
方案1:按Controller包路径匹配(零业务代码改造成本最低
如果你的所有返回JSON的API Controller都统一放在同一个根包下(比如com.yourproject.controller.api),只需要添加如下配置即可为该包下所有Controller自动统一加/api前缀,静态资源、页面跳转Controller完全不受影响:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebPrefixConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { // 替换为你实际的API Controller所在的根包路径 configurer.addPathPrefix("/api", clazz -> clazz.getPackage().getName().startsWith("com.yourproject.controller.api")); } }
方案2:自定义注解匹配(灵活性更高)
如果你的API Controller没有统一存放,你可以自定义一个标记注解,只给标注了该注解的Controller添加/api前缀:
- 首先自定义注解:
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ApiRestController { }
- 给所有需要加/api前缀的API Controller添加
@ApiRestController注解(可以直接替换原来的@RestController,也可以和@Controller叠加使用) - 添加路径前缀配置:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.PathMatchConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebPrefixConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.addPathPrefix("/api", clazz -> clazz.isAnnotationPresent(ApiRestController.class)); } }
配置效果说明
- 匹配规则完全满足你的需求:
- API接口自动统一携带/api前缀,不需要逐个修改Controller的
@RequestMapping - /、/login、/404page等页面路径、静态资源(图片、CSS、HTML)访问路径保持不变,正常返回对应资源
- 静态资源映射沿用Spring Boot默认规则,不需要额外调整静态资源配置
内容的提问来源于stack exchange,提问作者songgunho
相关产品推荐
相关产品推荐

