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

前因

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

效果

相关推荐
gb421528717 分钟前
java中将租户ID包装为JSQLParser的StringValue表达式对象,JSQLParser指的是?
java·开发语言·python
曾经的三心草28 分钟前
Python2-工具安装使用-anaconda-jupyter-PyCharm-Matplotlib
android·java·服务器
Metaphor69229 分钟前
Java 高效处理 Word 文档:查找并替换文本的全面指南
java·经验分享·word
ChinaRainbowSea43 分钟前
7. LangChain4j + 记忆缓存详细说明
java·数据库·redis·后端·缓存·langchain·ai编程
stormsha44 分钟前
飞算JavaAI炫技赛电商系统商品管理模块的架构设计与实现
java·架构·鸿蒙系统
minh_coo1 小时前
Spring框架事件驱动架构核心注解之@EventListener
java·后端·spring·架构·intellij-idea
enjoy嚣士1 小时前
springboot 之 HTML与图片生成 (2)
spring boot·html转图片
翻滚丷大头鱼1 小时前
Java 集合Collection—List
java·开发语言
sanggou1 小时前
License 集成 Spring Gateway:解决 WebFlux 非阻塞与 Spring MVC Servlet 阻塞兼容问题
spring·gateway·mvc
敲键盘的肥嘟嘟左卫门1 小时前
StringBuilder类的数据结构和扩容方式解读
java