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

前因

在一个服务中,既定义了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

效果

相关推荐
Wang's Blog15 分钟前
Java 接入Redis: Redis下载与源码编译安装
java·服务器·redis
农民工老王19 分钟前
故障排查:反向代理转发 GET 请求时 JDK 自动追加 Content-Length:0 致后端 500
java·httpclient·content-length
泡海椒21 分钟前
jquick-pdf 防止 PDF 内容分页断裂:keepTogether 属性妙用
java·开发语言·pdf
vx_BS8133023 分钟前
【项目编号:project51381】Spring Boot 婚纱摄影管理系统:套餐预约、在线咨询、支付与客片展示的一站式业务实现
java·spring boot·eclipse·tomcat·mybatis
IT毕设实战小研24 分钟前
基于大数据的商场商铺数据分析与可视化的设计与实现
android·java·大数据·django·课程设计
万年咸鱼25 分钟前
Java Classpath 详解:从原理到实战
java
雪芽蓝域zzs28 分钟前
第11节:分页查询(MyBatis 实现分页,后端最常用功能)
spring boot
Ivanqhz39 分钟前
矩阵引擎的数据流模式与 BM1684X 架构
java·服务器·网络·深度学习·神经网络
小蒜学长39 分钟前
大学生健康饮食的智慧管理系统(代码+数据库+LW)
java·后端·springboot·大学生·健康饮食
计算机毕设定制辅导-无忧学长41 分钟前
《基于SpringBoot的中学教师数字胜任力测评网站的设计与实现》
java·vue.js·spring boot·mysql·中学教师数字胜任力测评网站