背景
spring cloud 项目使用feign的时候都会发现一个问题,就是get方式无法解析对象参数。
其实 OpenFeign 提供了 @QueryMap 注解支持Map形式的参数转换。 但不幸的是和 Spring 不适配,因为缺少 value 这个属性,所以推荐使用 @SpringQueryMap 以解决 GET 请求的时候, 传递对象属性的问题。
问题
但是问题又来了,当使用子对象继承父类的时候会无法传递父类的属性。
探究源码
查看源码发现,默认使用的 QueryMapEncoder 是 FieldQueryMapEncoder,
而 FieldQueryMapEncoder 已废弃,推荐BeanQueryMapEncoder。
public interface QueryMapEncoder {
/**
* Encodes the given object into a query map.
*
* @param object the object to encode
* @return the map represented by the object
*/
Map<String, Object> encode(Object object);
/**
* @deprecated use {@link BeanQueryMapEncoder} instead. default encoder uses reflection to inspect
* provided objects Fields to expand the objects values into a query string. If you
* prefer that the query string be built using getter and setter methods, as defined
* in the Java Beans API, please use the {@link BeanQueryMapEncoder}
*/
class Default extends FieldQueryMapEncoder {
}
}
解决方案
@Configuration
public class FeignClientCustomizerConfig {
/**
* 替换解析 queryMap 的类,实现父类中变量的映射
* @return
*/
@Bean
public Feign.Builder feignBuilder() {
return Feign.builder()
.queryMapEncoder(new BeanQueryMapEncoder());
}
}
/**
* 指定client添加配置类
*/
@FeignClient(value = "micro-service", configuration = FeignClientCustomizerConfig.class)
// 或者
/**
* 主类添加配置类
*/
@EnableFeignClients(defaultConfiguration = FeignClientCustomizerConfig.class)
- BTW
此方式可以同时自定义 exceptionPropagationPolicy、retryer、encoder、decoder、decode404 等配置。
Reference
- https://www.whatyun.cn/article/934
- https://blog.csdn.net/li295214001/article/details/90410945