Dan*_*lor 30 java spring annotations spring-mvc jackson
我不合理地通过注释而不是纯xml bean来配置spring bean,现在我正面临着后果.
我使用配置REST通道
<mvc:annotation-driven />
Run Code Online (Sandbox Code Playgroud)
现在我只想配置MappingJacksonHttpMessageConverter
输出到JSON只有具有非空值的字段.我尝试过以下方法:
<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>
Run Code Online (Sandbox Code Playgroud)
Bean已创建,但转换器的另一个实例已创建并在通道中使用.所以我已经尝试过这个Stackoverflow问题@Configuration
并@Bean
在其中描述,但json序列化仍然使用自己的配置.
最后我试图通过注入mapper
@Autowired
private MappingJacksonHttpMessageConverter jacksonConverter;
Run Code Online (Sandbox Code Playgroud)
但我结束了NoSuchBeanDefinitionException
.所以现在我没有选择,所以我在这里要求任何想法.如何控制和配置框架使用的映射器?
Tom*_*icz 59
使用WebMvcConfigurer.configureMessageConverters()
方法:
配置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;
}
}
Run Code Online (Sandbox Code Playgroud)
调用addDefaultHttpMessageConverters()
是必需的,因为使用自定义转换器时不会应用默认值.
重要说明@EnableWebMvc
如果扩展WebMvcConfigurationSupport,则 必须删除要配置的转换器.
Jos*_*ias 27
仅在java代码中定制spring mvc servlet配置可以通过多种方式完成.
最简单的似乎是扩展您的@Configuration
注释类WebMvcConfigurerAdapter
:
@Configuration
@EnableWebMvc
public class ApplicationSpringConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) {
converters.add(converter());
}
@Bean
MappingJackson2HttpMessageConverter converter() {
// [...]
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,这很像Tomasz Nurkiewicz的答案所提供的示例.
但是,使用WebMvcConfigurationSupport
而不是WebMvcConfigurerAdapter
更适合高级自定义.如果您还需要添加默认转换器,则会出现这种情况.
请参阅Spring文档自定义提供的配置
归档时间: |
|
查看次数: |
66564 次 |
最近记录: |