其他分享
首页 > 其他分享> > 消息序列化spring简直为我们做的太多了,差点我都不会自己序列化了

消息序列化spring简直为我们做的太多了,差点我都不会自己序列化了

作者:互联网

前言

HttpMessageConverter

疑问

/**
 * Strategy interface that specifies a converter that can convert from and to HTTP requests and responses.
 * 用于实现request到response之间数据互转的接口
 */
public interface HttpMessageConverter<T> {}

请求入口

public RequestMappingHandlerAdapter() {
   this.messageConverters = new ArrayList<>(4);
   this.messageConverters.add(new ByteArrayHttpMessageConverter());
   this.messageConverters.add(new StringHttpMessageConverter());
   try {
      this.messageConverters.add(new SourceHttpMessageConverter<>());
   }
   catch (Error err) {
      // Ignore when no TransformerFactory implementation is available
   }
   this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
}
/**
 * 定制消息转换器, 控制对象序列化格式
 */
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    //converters.clear();
    converters.add(getFormHttpMessageConverter());
    converters.add(getJsonHttpMessageConverter());
}

作用

public abstract class AbstractHttpMessageConverter<T> implements HttpMessageConverter<T>
public interface HttpMessageConverter<T> {

   /**
    * 标识指定class是否可以使用该转换器
    */
   boolean canRead(Class<?> clazz, @Nullable MediaType mediaType);

   /**
    * 该转换器是否支持将该class写出
    */
   boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType);

   /**
    * 该转换器支持的请求头设置的mediaType
    */
   List<MediaType> getSupportedMediaTypes();

   /**
    * 从输入字节流中读取出指定class的数据
    */
   T read(Class<? extends T> clazz, HttpInputMessage inputMessage)
         throws IOException, HttpMessageNotReadableException;

   /**
    * 将指定class的数据输出到字节流中
    */
   void write(T t, @Nullable MediaType contentType, HttpOutputMessage outputMessage)
         throws IOException, HttpMessageNotWritableException;

}

InvocableHandlerMethod

@Nullable
private HandlerMethodArgumentResolver getArgumentResolver(MethodParameter parameter) {
   HandlerMethodArgumentResolver result = this.argumentResolverCache.get(parameter);
   if (result == null) {
      for (HandlerMethodArgumentResolver resolver : this.argumentResolvers) {
         if (resolver.supportsParameter(parameter)) {
            result = resolver;
            this.argumentResolverCache.put(parameter, result);
            break;
         }
      }
   }
   return result;
}

扩展

作者:zxhtom
链接:https://juejin.cn/post/7023545265613176839

标签:HttpMessageConverter,spring,差点,add,RequestMappingHandlerAdapter,转换器,序列化,我们,服务端
来源: https://blog.csdn.net/yyyy_11119/article/details/120994915