其余自定义 HTTP 消息转换器 Spring Boot 1.2.3



我想使用 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。 对于任何想要实现多态性的人都可以使用这两个注释。

我相信您希望在扩展WebMvcConfigurerAdapter的配置类中使用configureMessageConverters方法配置这些消息转换器。 我自己用CSV内容的转换器完成了这项工作。 我在下面包含了该代码。此链接还显示了一个示例。 此链接也可能有所帮助。 似乎对于 Spring 配置,并不总是清楚配置事物的最佳位置。:) 让我知道这是否有帮助。

@Configuration
public class ApplicationWebConfiguration extends WebMvcConfigurerAdapter {
     @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        converters.add(new CsvMessageConverter());
    }
}

您还需要对 supports() 方法进行 top 修改,以便为转换器支持的类返回 true。 请参阅 Spring 文档了解 AbstractHttpMessageConverter 支持的方法。

相关内容

最新更新