spring boot 自定義消息轉換器

需求分析:在請求返回中,想統一返回的數據格式。在controller層中經過aop中的環繞通知實現了這個功能。可是在轉換的過程當中,提示沒有自定義的格式轉換器。全部咱們須要本身實現這個轉換器。spring

實現方式:經過繼承 AbstractHttpMessageConverter這個類來實現功能。json

public class ResultBeanConverter extends AbstractHttpMessageConverter<ResultBean> {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private static final String DEFAULT_SUBTYPE = "json";

    public ResultBeanConverter(){

        super(new MediaType("application", DEFAULT_SUBTYPE, DEFAULT_CHARSET));
    }

    @Override
    protected boolean supports(Class<?> aClass) {
        return ResultBean.class.isAssignableFrom(aClass);
    }

    @Override
    protected ResultBean readInternal(Class<? extends ResultBean> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
        return new ResultBean();
    }

    @Override
    protected void writeInternal(ResultBean resultBean, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

        StreamUtils.copy(resultBean.toString(), DEFAULT_CHARSET, httpOutputMessage.getBody());
    }
}

 

經過spring注入,解決問題。app

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(resultBeanConverter());
        super.extendMessageConverters(converters);
    }

    @Bean
    public ResultBeanConverter resultBeanConverter(){

        return new ResultBeanConverter();
    }
}
相關文章
相關標籤/搜索