如何知道spring boot使用哪个消息转换器?

时间:2015-12-12 10:02:19

标签: spring-boot

出于某种原因,我决定换到另一个message converter,我的代码在

之下
@Bean
public HttpMessageConverters customConverters() {
    HttpMessageConverter<?> additional = new FastJsonHttpMessageConverter();
    return new HttpMessageConverters(additional);
}

现在我想知道如何检查这个自定义转换器是否有效?我试图访问/beans,但只有这个

{
    bean: "customConverters",
    scope: "singleton",
    type: "org.springframework.boot.autoconfigure.web.HttpMessageConverters",
    resource: "com.foo.BarApplication",
    dependencies: [ ]
}

那么确实存在一些知道spring boot使用哪个消息转换器的方式吗?

2 个答案:

答案 0 :(得分:2)

因为我不太确定我的自定义转换器是否有效,所以我必须跟踪源代码。我克隆了spring框架然后将其附加到eclipse中,然后逐步调试并找到了一些东西。 在AbstractMessageConverterMethodProcessor.writeWithMessageConverters

for (HttpMessageConverter<?> messageConverter : this.messageConverters)

当观看this.messageConverters低于输出

[org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter@1eb0d2e8, com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@2026476b, org.springframework.http.converter.ByteArrayHttpMessageConverter@3287cbc7, org.springframework.http.converter.StringHttpMessageConverter@2c19dd3, org.springframework.http.converter.ResourceHttpMessageConverter@1afe28f1, org.springframework.http.converter.xml.SourceHttpMessageConverter@87129da, org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter@4a412e0, org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@a8528a2, org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter@61d720a3]

实际上它使用了com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter@2026476b

答案 1 :(得分:1)

dependencies数组中仅显示注入的依赖项。如果您执行类似

的操作
@Bean
public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
    return new FastJsonHttpMessageConverter();
}

@Bean
@Autowired
public HttpMessageConverters convertersToBeUsed(FastJsonHttpMessageConverter converter) {
    return new HttpMessageConverters(converter);
}

您会在列表中看到FastJsonHttpMessageConverter

如果要查看所有已注册的转换器,请在bean列表中查找HttpMessageConvertersAutoConfiguration。它看起来应该类似于:

{
   bean: "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration",
   scope: "singleton",
   type: "org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration$$EnhancerBySpringCGLIB$$9e15b021",
   resource: "null",
   dependencies: [
       "fastJsonHttpMessageConverter",
       "stringHttpMessageConverter"
   ]
}