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

前因

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

效果

相关推荐
AC赳赳老秦15 分钟前
时间开销自动统计:OpenClaw 记录工作任务时长、分析时间分配、给出优化建议
java·大数据·开发语言·python·自动化·deepseek·openclaw
名侦探72241 分钟前
构建 Agent 的五大难点与解决方案
java·大数据·人工智能
Demons_kirit44 分钟前
图库原理(以阿里云OSS为案例)
java·阿里云·云计算
SimonKing1 小时前
那个号称"对标 Spring"的国产框架 Solon,到底行不行?
java·后端·程序员
Lethehong1 小时前
飞算Java:从需求梳理到风险闭环,搭建云盾企业信息安全与权限管理平台
java·开发语言
霸道流氓气质1 小时前
SpringBoot中使用字典驱动的动态路由示例
java·spring boot·后端
万亿少女的梦1681 小时前
基于Spring Boot、Vue与MySQL的高校实习信息管理系统设计与实现
spring boot·mysql·vue·权限管理·restful api
学计算机的计算基1 小时前
操作系统八股文:进程与线程全面梳理(附调度算法+IPC+锁机制)
java·算法
wuqingshun3141591 小时前
请描述简单工厂模式的工作原理
java·简单工厂模式
大不点wow2 小时前
Spring 中 @Bean、@Component 与 @Configuration 的作用及底层逻辑
java·spring