自定义MessageConverter原理
# 310.自定义MessageConverter原理
之前我们分析了内容协商原理,现在就来讲讲自定义Converter的原理
# 需求
有什么我们会遇到这样的需求:
- 一个接口用来返回数据;
- 如果是浏览器发送的请求,则返回XML
- 如果是Ajax发送的请求,则返回JSON
- 如果是App端发送的请求,则返回自定义协议数据(假设协议名字叫
x-guigu
)
如果是之前,一般是要写3个方法,分别给浏览器、Ajax和App返回数据。有了内容协商,我们就可以用一个方法兼容各种请求,根据不同请求返回不同类型,只需前端在发送请求的时候,加上想要的数据类型即可
实现步骤:
- 添加自定义的MessageConverter,到系统底层的Converter集合中
- 项目启动时,系统底层就会统计出所有MessageConverter能操作哪些类型
- 客户端发送数据,服务器返回数据
我们先分析下系统默认的Converter是如何加载的,再说下如何添加
# 加载Converter的过程
SpringBoot是用 xxxAutoConfiguration类来加载配置的,web开发相关的则是WebMvcAutoConfiguration
类;
在214行,有这样的配置:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
this.messageConvertersProvider.ifAvailable((customConverters) -> converters.addAll(customConverters.getConverters()));
}
2
3
4
我们点进customConverters.getConverters()
方法,就会来点HttpMessageConverters
类:
public List<HttpMessageConverter<?>> getConverters() {
return this.converters;
}
2
3
而converters这个成员变量,是在HttpMessageConverters
创建的时候,就会初始化的:
public HttpMessageConverters(boolean addDefaultConverters, Collection<HttpMessageConverter<?>> converters) {
List<HttpMessageConverter<?>> combined = getCombinedConverters(converters,
addDefaultConverters ? getDefaultConverters() : Collections.emptyList());
combined = postProcessConverters(combined);
this.converters = Collections.unmodifiableList(combined);
}
2
3
4
5
6
也就是会将调用addDefaultConverters
方法,获取默认的Converter;而addDefaultConverters
则是调用父类的getMessageConverters
方法( 在185行):
我们逐步分析,就会来到WebMvcConfigurationSupport
类,然后其就会加载Converter(例如前几行代码就加了不少Converter):
protected final void addDefaultHttpMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new ResourceHttpMessageConverter());
messageConverters.add(new ResourceRegionHttpMessageConverter());
try {
messageConverters.add(new SourceHttpMessageConverter<>());
}
catch (Throwable ex) {
// Ignore when no TransformerFactory implementation is available...
}
messageConverters.add(new AllEncompassingFormHttpMessageConverter());
if (romePresent) {
messageConverters.add(new AtomFeedHttpMessageConverter());
messageConverters.add(new RssChannelHttpMessageConverter());
}
if (jackson2XmlPresent) {
Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.xml();
if (this.applicationContext != null) {
builder.applicationContext(this.applicationContext);
}
messageConverters.add(new MappingJackson2XmlHttpMessageConverter(builder.build()));
}
else if (jaxb2Present) {
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
}
//....
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
第19行,还可以看到其会判断是否导入了Jackson的依赖,是就会加载响应的Converter
ps:jackson2XmlPresent这个变量,是在
WebMvcConfigurationSupport
的静态代码块加载的:static { ClassLoader classLoader = WebMvcConfigurationSupport.class.getClassLoader(); romePresent = ClassUtils.isPresent("com.rometools.rome.feed.WireFeed", classLoader); jaxb2Present = ClassUtils.isPresent("javax.xml.bind.Binder", classLoader); jackson2Present = ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", classLoader) && ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", classLoader); jackson2XmlPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.xml.XmlMapper", classLoader); jackson2SmilePresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.smile.SmileFactory", classLoader); jackson2CborPresent = ClassUtils.isPresent("com.fasterxml.jackson.dataformat.cbor.CBORFactory", classLoader); gsonPresent = ClassUtils.isPresent("com.google.gson.Gson", classLoader); jsonbPresent = ClassUtils.isPresent("javax.json.bind.Jsonb", classLoader); }
1
2
3
4
5
6
7
8
9
10
11
# 新建Converter类
我们新增一个类GuiguMessageConverter
,实现HttpMessageConverter
接口,并且是操作Person类型的数据,然后实现接口中的方法:
package com.peterjxl.boot.converter;
import com.peterjxl.boot.bean.Person;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import java.io.IOException;
import java.util.List;
public class GuiguMessageConverter implements HttpMessageConverter<Person> {
@Override
public boolean canRead(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return false;
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return null;
}
@Override
public Person read(Class<? extends Person> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {
return null;
}
@Override
public void write(Person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
canRead
方法:我们目前只关系转换数据,因此可读就直接返回false;
canWrite
方法:是否可转换,我们只需判断类型是否一致即可,因此修改为:
@Override
public boolean canWrite(Class<?> clazz, MediaType mediaType) {
return clazz.isAssignableFrom(Person.class);
}
2
3
4
getSupportedMediaTypes
:获取支持的媒体类型,这个很重要,SpringBoot就是根据该方法,统计所有Converter能写出的媒体类型,例如application/xml
。这里修改如下:
@Override
public List<MediaType> getSupportedMediaTypes() {
return MediaType.parseMediaTypes("application/x-guigu");
}
2
3
4
read
方法:忽略
write
方法,就是用来转换自定义数据为Person对象的了。这里假设自定义类型的数据,格式是这样的:属性值1:属性值2;
,因此代码如下:
@Override
public void write(Person person, MediaType contentType, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
String data = person.getUserName() + ";" + person.getAge() + ";" + person.getBirth();
outputMessage.getBody().write(data.getBytes());
}
2
3
4
5
# 如何添加自定义Converter
首先,我们明确一点:修改SpringMVC的功能,都是通过在容器中添加一个WebMvcConfigurer
组件即可,在该组件内定制功能。、
WebMvcConfigurer
是一个接口,里面有这两个方法:
default void configureMessageConverters(List<HttpMessageConverter<?>> converters) {}
default void extendMessageConverters(List<HttpMessageConverter<?>> converters) {}
2
用configureMessageConverters,相当于会覆盖默认的Converter;
用extendMessageConverters,则是扩展,相当于在默认的Converter里添加新的Converter
我们在配置类WebConfig
中添加代码(第5 ~ 8行):
@Bean
public WebMvcConfigurer webMvcConfigurer(){
return new WebMvcConfigurer() {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(new GuiguMessageConverter());
}
//.......
2
3
4
5
6
7
8
9
10
为了方便编辑请求头,我们使用Postman来发送HTTP请求,在Accept字段上加上application/x-guigu
,然后发送,可以看到能正常返回数据:
至于添加了Converter后,内容协商的过程,其实是一样的,这里就不赘述了,感兴趣的同学可以自行debug来观察
# 以请求参数的方式完成内容协商
刚刚我们是用HTTP请求头的方式,现在我们就用请求参数的方式来完成。首先,默认情况下,基于请求参数的内容协商,只支持XML和JSON的格式:
那怎么办呢?很简单,我们自定义一个策略,然后放入策略管理器即可。在WebMvcConfigurer
类中,就有相关的方法(第66行):
default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {}
我们来到WebConfig
配置类,添加如下代码:
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
Map<String, MediaType> mediaTypes = new HashMap<>();
mediaTypes.put("json", MediaType.APPLICATION_JSON);
mediaTypes.put("xml", MediaType.APPLICATION_XML);
mediaTypes.put("gg", MediaType.parseMediaType("application/x-guigu"));
ParameterContentNegotiationStrategy parameterContentNegotiationStrategy = new ParameterContentNegotiationStrategy(mediaTypes);
HeaderContentNegotiationStrategy headerContentNegotiationStrategy = new HeaderContentNegotiationStrategy();
configurer.strategies(Arrays.asList(parameterContentNegotiationStrategy, headerContentNegotiationStrategy));
}
2
3
4
5
6
7
8
9
10
11
注意:覆盖configureContentNegotiation
方法后,就得自行添加基于请求头的策略了,否则就只会有我们自己定义的策略
此时我们重启,能看到正常访问:
扩展知识点:我们请求参数中,名字默认是format,是可以自行修改的,例如改为
ff
:parameterContentNegotiationStrategy.setParameterName("ff")
1
# 源码
已将本文源码上传到Gitee (opens new window)或GitHub (opens new window) 的分支demo1,读者可以通过切换分支来查看本文的示例代码