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

前因

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

效果

相关推荐
Mos_x几秒前
Python爬虫---中国大学MOOC爬取数据(文中有
java·后端
_安晓43 分钟前
Rust 中精确大小迭代器(ExactSizeIterator)的深度解析与实践
java·前端·python
Javatutouhouduan1 小时前
记一次redis主从切换导致的数据丢失与陷入只读状态故障
java·redis·设计模式·java面试·高可用·java后端·java程序员
YDS8291 小时前
Redis入门 —— 基本数据类型和Spring Data Redis
数据库·redis·spring
CS Beginner2 小时前
【IDEA】记录webapp下创建相同目录的一次错误
java·intellij-idea·web app
donotshow2 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
java·后端
王元_SmallA3 小时前
Go环境搭建(vscode调试)
java·后端
陈果然DeepVersion3 小时前
Java大厂面试真题:Spring Boot+Kafka+AI智能客服场景全流程解析(六)
spring boot·kafka·消息队列·向量数据库·java面试·rag·ai智能客服
952364 小时前
数据结构-顺序表
java·数据结构·学习