feign改写默认编码器
时间: 2023-11-08 08:04:35 浏览: 102
覆写Feign的默认配置-代码部分.zip
可以通过继承Feign的Encoder.Default编码器类,并重写其encode方法来改写默认编码器。
重写的示例代码如下:
```
public class CustomEncoder extends Encoder.Default {
private final Gson gson;
public CustomEncoder(ObjectFactory objectFactory) {
this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
}
@Override
public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
if (bodyType != null && object != null) {
if (bodyType instanceof Class && (MediaType.APPLICATION_JSON_VALUE.equals(template.headers().get("Content-Type")) || MediaType.APPLICATION_JSON_VALUE.equals(template.headers().get("content-Type")))) {
String json = gson.toJson(object, bodyType);
template.body(json);
}
}
}
}
```
在Feign客户端接口中使用自定义编码器:
```
@FeignClient(name = "myService", configuration = MyFeignConfiguration.class)
public interface MyFeignClient {
@PostMapping(value = "/api/test", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
ResultVO<String> test(@RequestBody TestDTO testDTO);
}
```
在配置类中配置自定义编码器:
```
@Configuration
public class MyFeignConfiguration {
@Bean
public Encoder encoder() {
return new CustomEncoder(new SpringEncoder(new DefaultJackson2ObjectMapperBuilder()));
}
}
```
阅读全文