Spring Boot 接口统一前缀
创始人
2025-05-31 14:28:43

需求

需求如题,想给一个 spring boot 项目的所有请求路径添加统一前缀,可以通过 context-path 来配置。但是在同时存在静态资源和 Controller 接口的项目中,如果希望静态资源从根路径访问,并且所有接口拥有统一路径前缀,则需要通过 Spring 层面来解决这个问题(context-path 是 web 容器层面的,如果配置它则会把静态资源都包含进去)。

如下接口示例:

# 3个静态资源
http://localhost:8080/index.html
http://localhost:8080/home.js
http://localhost:8080/dog.png# 3个统一前缀为 /api
http://localhost:8080/api/test/show
http://localhost:8080/api/test/display
http://localhost:8080/api/test/print

如上URL示例中,希望放在 springboot 根目录 static 中的静态资源能直接通过根路径访问。其他 Controller 接口的前缀 “/api” 可以在配置文件中自定义配置变更。

实现

实现方法很简单,如下代码和配置文件:

1、GlobalControllerPathPrefixConfiguration.java

package com.example.demospringbean;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** 为 Controller 接口配置统一前缀** @author shanhy* @date 2023-03-20 15:50*/
@Configuration
public class GlobalControllerPathPrefixConfiguration implements WebMvcConfigurer {@Value("${spring.controller.path-prefix:}")private String pathPrefix;@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.addPathPrefix(pathPrefix, c -> c.isAnnotationPresent(RestController.class));}}

2、application.properties

spring.controller.path-prefix=/api

配置文件中参数 spring.controller.path-prefix 也可以是多级路径,例如 /api/demo

3、TestController.java

/*** 接口示例* * @author shanhy* @date 2023-03-20 15:49*/
@RestController
@RequestMapping("/test")
public class TestController {@GetMapping("/show")public String show(){return "OK";}}

最后将 dog.png 放在 springboot 项目的 static 目录中用来测试。

验证

打开浏览器分别访问如下路径可以正常显示结果,表示成功。

http://localhost:8080/dog.png
http://localhost:8080/api/test/show


(END)

相关内容

热门资讯

世界上最漂亮的人 世界上最漂亮... 此前在某网上,选出了全球265万颜值姣好的女性。从这些数量庞大的女性群体中,人们投票选出了心目中最美...
应用未安装解决办法 平板应用未... ---IT小技术,每天Get一个小技能!一、前言描述苹果IPad2居然不能安装怎么办?与此IPad不...
猫咪吃了塑料袋怎么办 猫咪误食... 你知道吗?塑料袋放久了会长猫哦!要说猫咪对塑料袋的喜爱程度完完全全可以媲美纸箱家里只要一有塑料袋的响...
重庆属于哪个省份的 重庆在中国... 重庆有多大,大到超出我们的想象,重庆作为我国4个直辖市之一,印象里应该跟京津沪面积差不多,可事实上却...
阿西吧是什么意思 阿西吧相当于... 即使你没有受到过任何外语培训,你也懂四国语言。汉语:你好英语:Shit韩语:阿西吧(아,씨발! )日...