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

前因

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

效果

相关推荐
guangzhi06336 分钟前
JVM本地方法栈
java·jvm·面试
akhfuiigabv11 分钟前
使用LangChain创建简单的语言模型应用程序【快速入门指南】
java·python·语言模型·langchain
忘却的纪念18 分钟前
基于SpringBoot的考研资讯平台设计与实现
java·spring boot·spring
.生产的驴20 分钟前
SpringBoot 消息队列RabbitMQ死信交换机
java·spring boot·后端·rabbitmq·java-rabbitmq
振华OPPO21 分钟前
我的5周年创作纪念日,不忘初心,方得始终。
android·java·android studio·安卓·安卓app
抚月code24 分钟前
Java线程池
java
IT枫斗者29 分钟前
集合工具类
java·linux·数据库·windows·算法·microsoft
会敲代码的小张41 分钟前
设计模式-观察者模式
java·开发语言·后端·观察者模式·设计模式·代理模式
程序猿!=程序员4 小时前
JAVA学习路线
java
Rivieres4 小时前
算法入门-贪心1
java·算法·leetcode·推荐算法