[OpenFeign] SpringBoot RequestMapping 默认decodeSlash

场景

在某个项目中,某个OpenFeign的 RequestMapping地址是 /api/v3/projects/{projectId}/repository/branches
,其中 projectId 可能含有斜杠,例如 a/b 编码成 a%2Fb,而我们希望传后者,但是OpenFeign会将这个%2F进行decode。

因此,要解决的问题:如何手动关闭OpenFeign解码反斜杠

期望结果

例如 projectId=a/b
请求发送的时候应该是
/api/v3/projects/a%2Fb/repository/branches
而不是
/api/v3/projects/a/b/repository/branches

分析

在SpringBoot的环境中,Spring通过SpringMvcContract来处理Spring的注解到OpenFeign的桥接和适配。

SpringMvcContract 在 OpenFeign的 自动装配类 FeignClientsConfiguration内声明。

	@Bean
	@ConditionalOnMissingBean
	public Contract feignContract(ConversionService feignConversionService) {
		boolean decodeSlash = feignClientProperties == null || feignClientProperties.isDecodeSlash();
		return new SpringMvcContract(this.parameterProcessors, feignConversionService, decodeSlash);
	}

可以看到FeignClientProperties的decodeSlash默认是true。除非配置了 feign.client.decodeSlash=false

解决

全局解决

feign.client.decodeSlash=false

最小影响范围

可以使用FeignClient的单独配置覆盖全局配置

参考链接 spring-cloud-feign-overriding-defaults

@slankka

@FeignClient(name = "yourClient", url= "slankka.com", configuration = YourClient.ClientConf.class)
public interface YourClient {
  class ClientConf{
     @Bean
          Contract contract(@Autowired(required = false) List<AnnotatedParameterProcessor> parameterProcessors,
                            ConversionService feignConversionService) {
              if (parameterProcessors == null) {
                  parameterProcessors = new ArrayList<>();
              }
              return new SpringMvcContract(parameterProcessors, feignConversionService, false);
          }
   }
}

参考 Issue

大神请直接移步:https://github.com/OpenFeign/feign/issues/1190

posted @ 2023-01-13 17:24  一杯半盏  阅读(255)  评论(0编辑  收藏  举报