SpringBoot多controller如何添加URL前缀(controller,springboot,URL,开发技术)

时间:2024-05-02 08:09:32 作者 : 石家庄SEO 分类 : 开发技术
  • TAG :
前言

在某些情况下,服务的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

二、配置映射的实体

@Data@Component@ConfigurationProperties(prefix="api.prefix")publicclassApiPrefix{privateStringv1;}

三、自定义注解

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

@RestController@Documented@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public@interfaceApiV1RestController{}

四、自定义PathMatch添加前缀

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

@AutoConfigurationpublicclassWebMvcConfigimplementsWebMvcConfigurer{@AutowiredprivateApiPrefixapiPrefix;@OverridepublicvoidconfigurePathMatch(PathMatchConfigurerconfigurer){configurer.addPathPrefix(apiPrefix.getV1(),c->c.isAnnotationPresent(ApiV1RestController.class));}}

五、测试

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

@ApiV1RestController@RequestMapping("/test/apiv1")publicclassTestApiV1RestController{@GetMapping()publicResponseEntityget(){returnnewResponseEntity();}}

SpringBoot多controller如何添加URL前缀

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:SpringBoot多controller如何添加URL前缀的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:js怎么实现中文实时时钟下一篇:

3 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18