0


Java:SpringBoot给Controller添加统一路由前缀

网上的文章五花八门,不写SpringBoot的版本号,导致代码拿来主义不好使了。

本文采用的版本

SpringBoot 2.7.7
Java 1.8

目录

1、默认访问路径

packagecom.example.demo.controller.api;importorg.springframework.web.bind.annotation.GetMapping;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/api")publicclassAppIndexController{@GetMapping("/index")publicStringindex(){return"app";}}

访问地址:http://localhost:8080/api/index

2、整个项目增加路由前缀

application.yml

server:servlet:context-path: /prefix

访问地址:http://localhost:8080/prefix/api/index

注意:该方案会将所有的路由都增加一个前缀

3、通过注解方式增加路由前缀

注解

packagecom.example.demo.annotation;importorg.springframework.core.annotation.AliasFor;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RestController;importjava.lang.annotation.*;/**
 * controller层统一使用该注解
 */@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@RestControllerpublic@interfaceApiRestController{/**
     * Alias for {@link Controller#value}.
     */@AliasFor(annotation =Controller.class)Stringvalue()default"";}

配置

packagecom.example.demo.config;importcom.example.demo.annotation.ApiRestController;importorg.springframework.context.annotation.Configuration;importorg.springframework.web.servlet.config.annotation.PathMatchConfigurer;importorg.springframework.web.servlet.config.annotation.WebMvcConfigurer;/**
 * 配置统一的后台接口访问路径的前缀
 */@ConfigurationpublicclassCustomWebMvcConfigimplementsWebMvcConfigurer{@OverridepublicvoidconfigurePathMatch(PathMatchConfigurer configurer){
        configurer
                .addPathPrefix("/api", c -> c.isAnnotationPresent(ApiRestController.class));}}

使用注解

packagecom.example.demo.controller.api;importcom.example.demo.annotation.ApiRestController;importorg.springframework.web.bind.annotation.GetMapping;@ApiRestController// @RestController// @RequestMapping("/api")publicclassAppIndexController{@GetMapping("/index")publicStringindex(){return"app";}}

访问地址:http://localhost:8080/api/index

4、按照目录结构添加前缀

没有成功,可能是版本的问题

Neither PathPatterns nor String patterns condition

参考文章

  • SpringBoot2.x 给Controller的RequestMapping添加统一前缀
  • SpringBoot - 根据目录结构自动生成路由前缀
标签: java spring boot spring

本文转载自: https://blog.csdn.net/mouday/article/details/129520772
版权归原作者 彭世瑜 所有, 如有侵权,请联系我们删除。

“Java:SpringBoot给Controller添加统一路由前缀”的评论:

还没有评论