Spring和jackson,如何通过@ResponseBody禁用FAIL_ON_EMPTY_BEANS [英] Spring and jackson, how to disable FAIL_ON_EMPTY_BEANS through @ResponseBody
问题描述
春天是否有全局配置可以为所有使用@ResponseBody注释的控制器禁用弹簧FAIL_ON_EMPTY_BEANS?
Is there a global configuration in spring that can disable spring FAIL_ON_EMPTY_BEANS for all controller annotated with @ResponseBody?
推荐答案
你可以配置 configureMessageConverters时配置对象映射器
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter(mapper);
return converter;
}
如果您想知道如何在您的申请中做到完全,请更新您的配置文件的问题(xml或java配置)。
If you want to know how to do exactly in your application, please update your question with your configuration files (xml or java configs).
这是一个很好的文章如何自定义邮件转换器。
Here is a good article how to customize message converters.
编辑:如果您使用的是XML而不是Java配置,则可以创建一个自定义 MyJsonMapper
使用自定义配置扩展 ObjectMapper
的类,然后按如下方式使用
If you are using XML instead of Java configs, you can create a custom MyJsonMapper
class extending ObjectMapper
with custom configuration, and then use it as follows
public class MyJsonMapper extends ObjectMapper {
public MyJsonMapper() {
this.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
}
在您的XML中:
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<bean id="jacksonObjectMapper" class="com.mycompany.example.MyJsonMapper" >
这篇关于Spring和jackson,如何通过@ResponseBody禁用FAIL_ON_EMPTY_BEANS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!