问题描述
我是不合理的,足以走进通过注释,而不是纯粹的XML配置豆类豆类春,现在我面临的后果。
I was unreasonable enough to went into configuring spring beans via annotations and not pure xml beans and now I'm facing the consequences.
我配置使用REST渠道
I configure REST channels using
<mvc:annotation-driven />
现在我想简单的配置 MappingJacksonHttpMessageConverter
来输出JSON仅此领域具有非空值。我已经试过如下:
Now I want simply configure the MappingJacksonHttpMessageConverter
to output to JSON only this fields that have non-null values. I've tried the following:
<bean id="jsonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="prefixJson" value="false" />
<property name="supportedMediaTypes" value="application/json" />
<property name="objectMapper">
<bean class="org.codehaus.jackson.map.ObjectMapper">
<property name="serializationInclusion" value="NON_NULL"/>
</bean>
</property>
</bean>
豆被创建,但是创建并在信道使用的转换器的另一实例。所以,我已经试过的方式与 @Configuration
和 @Bean
中所描述的,但仍JSON序列化使用其自己的配置。
The beans gets created, but another instance of converter is created and used in channels. So I've tried the way with @Configuration
and @Bean
described in this Stackoverflow question, but still json serialization uses its own configuration.
最后,我试图注入映射器通过
Finally I've tried to inject the mapper via
@Autowired
private MappingJacksonHttpMessageConverter jacksonConverter;
但我已经对 NoSuchBeanDefinitionException
结束。所以我现在没办法了,所以我问这里的任何想法。如何控制好并配置框架使用的映射?
but I've ended with NoSuchBeanDefinitionException
. So now I'm out of options and therefore I'm asking for any ideas here. How to controll and configure the mapper used by framework?
推荐答案
使用的<$c$c>WebMvcConfigurer.configureMessageConverters()$c$c>方法:
配置HttpMessageConverters使用[...]如果没有消息转换器添加到列表中,缺省转换器代替加入
使用 @Configuration
您有:
@Configuration
class MvcConf extends WebMvcConfigurationSupport {
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
addDefaultHttpMessageConverters(converters);
}
@Bean
MappingJacksonHttpMessageConverter converter() {
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter()
//do your customizations here...
return converter;
}
}
电话 addDefaultHttpMessageConverters()
是必需的,因为使用自定义转换器时的默认设置不被应用。
Call to addDefaultHttpMessageConverters()
is required because the defaults are not applied when using custom converters.
重要提示您必须删除 @EnableWebMvc
对于要配置的转换器,如果你扩展WebMvcConfigurationSupport。
IMPORTANT NOTE You must remove @EnableWebMvc
for your converters to be configured if you extend WebMvcConfigurationSupport.
这篇关于如何同时使用基于注解Spring配置文件来配置MappingJacksonHttpMessageConverter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!