其他分享
首页 > 其他分享> > Rest Custom HTTP Message Converter Spring Boot 1.2.3

Rest Custom HTTP Message Converter 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内容转换器.我在下面包含了该代码. This link也显示了一个示例. This link也可能会有所帮助.对于Spring配置来说,似乎并不总是在最佳的地方进行配置. :)让我知道这是否有帮助.

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

您还需要顶部修改您的supports()方法以为转换器支持的类返回true.参见the Spring doc for AbstractHttpMessageConverter supports method.

标签:spring-4,spring-boot,spring-restcontroller,spring-json,spring
来源: https://codeday.me/bug/20191120/2042006.html