经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring Boot » 查看文章
SpringBoot多controller添加URL前缀的实现方法
来源:jb51  时间:2023/2/17 9:58:55  对本文有异议

前言

在某些情况下,服务的controller中前缀是一致的,例如所有URL的前缀都为/context-path/api/v1,需要为某些URL添加统一的前缀。

能想到的处理办法为修改服务的context-path,在context-path中添加api/v1,这样修改全局的前缀能够解决上面的问题,但存在弊端,如果URL存在多个前缀,例如有些URL需要前缀为api/v2,就无法区分了,如果服务中的一些静态资源不想添加api/v1,也无法区分。

下面通过自定义注解的方式实现某些URL前缀的统一添加。

一、配置文件内添加前缀配置

如果需要多种前缀,添加多组配置,例如添加:api.prefix.v2=/api/v2

###############url前缀配置##################
api.prefix.v1=/api/v1

二、配置映射的实体

  1. @Data
  2. @Component
  3. @ConfigurationProperties(prefix = "api.prefix")
  4. public class ApiPrefix {
  5. private String v1;
  6. }

三、自定义注解

此注解功能与@RestController一致,对应api.prefix.v1的配置,如果有多组配置,定义多个注解即可

  1. @RestController
  2. @Documented
  3. @Target(ElementType.TYPE)
  4. @Retention(RetentionPolicy.RUNTIME)
  5. public @interface ApiV1RestController {
  6. }

四、自定义PathMatch添加前缀

添加一个配置类继承WebMvcConfigurer,重写configurePathMatch方法,为类上有ApiV1RestController注解的controller中的接口添加对应的前缀。

  1. @AutoConfiguration
  2. public class WebMvcConfig implements WebMvcConfigurer {
  3. @Autowired
  4. private ApiPrefix apiPrefix;
  5. @Override
  6. public void configurePathMatch(PathMatchConfigurer configurer) {
  7. configurer.addPathPrefix(apiPrefix.getV1(), c -> c.isAnnotationPresent(ApiV1RestController.class));
  8. }
  9. }

五、测试

需要在对应的controller上使用@ApiV1RestController注解代替@RestController注解

  1. @ApiV1RestController
  2. @RequestMapping("/test/apiv1")
  3. public class TestApiV1RestController {
  4. @GetMapping()
  5. public ResponseEntity get() {
  6. return new ResponseEntity();
  7. }
  8. }

到此这篇关于SpringBoot多controller添加URL前缀的实现方法的文章就介绍到这了,更多相关SpringBoot添加URL前缀内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号