当前位置: 首页> 财经> 创投人物 > 在定义的接口前加前缀路径

在定义的接口前加前缀路径

时间:2025/7/11 14:59:11来源:https://blog.csdn.net/qq_30686255/article/details/141472151 浏览次数:0次

前因

在一个服务中,既定义了app端接口,又定义了pc端接口,为了方便区分,可以在项目里建立一个名为"app"、"pc"的文件夹,分别为app、pc提供接口。当app和pc接口一致时,写完一端接口后,可以直接拷贝到另一文件夹,直接使用。但当不加前缀的情况下,因接口定义一致,会出现异常。这时候在接口前添加前缀,就可以解决这个问题。

实现步骤

  • 定义一个配置类,实现WebMvcConfigurer,重写configurePathMatch方法,指定添加前缀
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@AutoConfiguration
public class MyWebAutoConfiguration implements WebMvcConfigurer {public void configurePathMatch(PathMatchConfigurer configurer) {AntPathMatcher antPathMatcher = new AntPathMatcher(".");configurer.addPathPrefix("/app-api", (clazz) -> {return clazz.isAnnotationPresent(RestController.class) && antPathMatcher.match("**.example.my_2024_demo.ctrl.app.**", clazz.getPackage().getName());});configurer.addPathPrefix("/pc-api", (clazz) -> {return clazz.isAnnotationPresent(RestController.class) && antPathMatcher.match("**.example.my_2024_demo.ctrl.pc.**", clazz.getPackage().getName());});}
}
  • ctrl 接口定义文件目录如下图,与上一步指定路径相对应
    在这里插入图片描述
    代码
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class AppTestCtrl {@GetMapping("/test")private String test(HttpServletRequest request) {request.setAttribute("name", "用于测试信息");return "app test";}}
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class PcTestCtrl {@GetMapping("/test")private String test(HttpServletRequest request) {request.setAttribute("name", "用于测试信息");return "pc test";}
}
  • 接口访问
    pc端:http://localhost:8080/pc-api/test
    效果
    在这里插入图片描述

app端:http://localhost:8080/app-api/test
效果
在这里插入图片描述

关键字:在定义的接口前加前缀路径

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: