首页>>后端>>Spring->Spring 源码解析:消息转换

Spring 源码解析:消息转换

时间:2023-11-29 本站 点击:0

消息转换器定义

我们可以通过重写 configureMessageConverters()方法(替换Spring MVC创建的默认转换器)或重写extendMessageConverters()方法(自定义默认转换器或向默认转换器添加其他转换器)在Java配置中自定义 HttpMessageConverter。

HttpMessageConverter

消息转换器 HttpMessageConverter 借口定义如下:

publicinterfaceHttpMessageConverter<T>{/***Indicateswhetherthegivenclasscanbereadbythisconverter.*@paramclazztheclasstotestforreadability*@parammediaTypethemediatypetoread(canbe{@codenull}ifnotspecified);*typicallythevalueofa{@codeContent-Type}header.*@return{@codetrue}ifreadable;{@codefalse}otherwise*/booleancanRead(Class<?>clazz,@NullableMediaTypemediaType);/***Indicateswhetherthegivenclasscanbewrittenbythisconverter.*@paramclazztheclasstotestforwritability*@parammediaTypethemediatypetowrite(canbe{@codenull}ifnotspecified);*typicallythevalueofan{@codeAccept}header.*@return{@codetrue}ifwritable;{@codefalse}otherwise*/booleancanWrite(Class<?>clazz,@NullableMediaTypemediaType);/***Returnthelistofmediatypessupportedbythisconverter.Thelistmay*notapplytoeverypossibletargetelementtypeandcallstothismethod*shouldtypicallybeguardedvia{@link#canWrite(Class,MediaType)*canWrite(clazz,null}.ThelistmayalsoexcludeMIMEtypessupported*onlyforaspecificclass.Alternatively,use*{@link#getSupportedMediaTypes(Class)}foramorepreciselist.*@returnthelistofsupportedmediatypes*/List<MediaType>getSupportedMediaTypes();/***Returnthelistofmediatypessupportedbythisconverterforthegiven*class.Thelistmaydifferfrom{@link#getSupportedMediaTypes()}ifthe*converterdoesnotsupportthegivenClassorifitsupportsitonlyfor*asubsetofmediatypes.*@paramclazzthetypeofclasstocheck*@returnthelistofmediatypessupportedforthegivenclass*@since5.3.4*/defaultList<MediaType>getSupportedMediaTypes(Class<?>clazz){return(canRead(clazz,null)||canWrite(clazz,null)?getSupportedMediaTypes():Collections.emptyList());}/***Readanobjectofthegiventypefromthegiveninputmessage,andreturnsit.*@paramclazzthetypeofobjecttoreturn.Thistypemusthavepreviouslybeenpassedtothe*{@link#canReadcanRead}methodofthisinterface,whichmusthavereturned{@codetrue}.*@paraminputMessagetheHTTPinputmessagetoreadfrom*@returntheconvertedobject*@throwsIOExceptionincaseofI/Oerrors*@throwsHttpMessageNotReadableExceptionincaseofconversionerrors*/Tread(Class<?extendsT>clazz,HttpInputMessageinputMessage)throwsIOException,HttpMessageNotReadableException;/***Writeangivenobjecttothegivenoutputmessage.*@paramttheobjecttowritetotheoutputmessage.Thetypeofthisobjectmusthavepreviouslybeen*passedtothe{@link#canWritecanWrite}methodofthisinterface,whichmusthavereturned{@codetrue}.*@paramcontentTypethecontenttypetousewhenwriting.Maybe{@codenull}toindicatethatthe*defaultcontenttypeoftheconvertermustbeused.Ifnot{@codenull},thismediatypemusthave*previouslybeenpassedtothe{@link#canWritecanWrite}methodofthisinterface,whichmusthave*returned{@codetrue}.*@paramoutputMessagethemessagetowriteto*@throwsIOExceptionincaseofI/Oerrors*@throwsHttpMessageNotWritableExceptionincaseofconversionerrors*/voidwrite(Tt,@NullableMediaTypecontentType,HttpOutputMessageoutputMessage)throwsIOException,HttpMessageNotWritableException;}

自定义消息转换器

下面是一个简单的消息转换器定义,代码如下:

@Configuration@EnableWebMvcpublicclassWebConfigurationimplementsWebMvcConfigurer{@OverridepublicvoidconfigureMessageConverters(List<HttpMessageConverter<?>>converters){Jackson2ObjectMapperBuilderbuilder=newJackson2ObjectMapperBuilder().indentOutput(true).dateFormat(newSimpleDateFormat("yyyy-MM-dd")).modulesToInstall(newParameterNamesModule());converters.add(newMappingJackson2HttpMessageConverter(builder.build()));converters.add(newMappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));}}

在前面的示例中,Jackson2ObjectMapperBuilder 用于为 MappingJackson2HttpMessageConverter 和MappingJackson2XmlHttpMessageConverter 创建公共配置,启用缩进、自定义日期格式和jackson模块参数名称注册,这增加了对访问参数名称的支持(Java8中添加的一个特性)。

配置 FastJson 为默认 JSON 解析器

其实我们在项目最最常用的还是 FastJSON 作为 Spring MVC 的默认 JSON 解析器。具体的配置如下:

<beanid="mappingJacksonHttpMessageConverter"class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter"><!--class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">--><propertyname="supportedMediaTypes"><list><value>text/html;charset=UTF-8</value><value>application/json</value><value>application/xml;charset=UTF-8</value></list></property></bean>

参考资料

https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-config-message-converters

https://blog.csdn.net/qq_37292960/article/details/86614725


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:/Spring/322.html