我想使用 Rest、Json、Spring Boot 1.2.3 和 Spring 4 创建一个自定义的 HttpMessageConverter,但是我的自定义 HTTPMessageConverter 它从未被调用过。
我已经执行了以下步骤:
1:创建了一个扩展 AbstractHttpMessageConverter 的类
@Component
public class ProductConverter extends AbstractHttpMessageConverter<Employee> {
public ProductConverter() {
super(new MediaType("application", "json", Charset.forName("UTF-8")));
System.out.println("Created ");
}
@Override
protected boolean supports(Class<?> clazz) {
return false;
}
@Override
protected Employee readInternal(Class<? extends Employee> clazz,
HttpInputMessage inputMessage) throws IOException,
HttpMessageNotReadableException {
InputStream inputStream = inputMessage.getBody();
System.out.println("Test******");
return null;
}
@Override
protected void writeInternal(Employee t,
HttpOutputMessage outputMessage) throws IOException,
HttpMessageNotWritableException {
// TODO Auto-generated method stu
}
}
2:我创建一个配置类来注册HTTPMessageConverters
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter{
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
System.out.println("Configure Message Converters");
converters.add(new ProductConverter());
super.configureMessageConverters(converters);
//super.extendMessageConverters(converters);
}
}
3:休息类方法
@RequestMapping(value="/{categoryId}" ,method=RequestMethod.POST, consumes="application/json")
@PreAuthorize("permitAll")
public ResponseEntity<ProductEntity> saveProduct(@RequestBody Employee employee , @PathVariable Long categoryId) {
logger.log(Level.INFO, "Category Id: {0}" , categoryId);
ResponseEntity<ProductEntity> responseEntity =
new ResponseEntity<ProductEntity>(HttpStatus.OK);
return responseEntity;
}
我的自定义 HTTPMessageCoverter 它已创建但从未被调用?是否有我缺少的配置或步骤?任何意见或建议表示赞赏。
重写(AbstractHttpMessageConverter)类方法后,我发现有两个注释可以实现多态@JsonTypeInfo 和@JsonSubTypes。对于任何想要实现多态性的人都可以使用这两个注释。