为单个 Spring Controller 指定消息转换器 [英] Specify message converters for single Spring Controller

查看:48
本文介绍了为单个 Spring Controller 指定消息转换器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为具有一些奇怪的 JSON 映射实践的服务编写回发处理程序库.我可以很容易地配置一个自定义的 Jackson ObjectMapper 来处理映射,但是如果我用那个映射器注册一个 Spring MVC 消息转换器,它就会应用映射(这对于我的 JSON 的其余部分是不正确的)m 处理) 到所有传入请求.

I'm writing a postback handler library for a service that has some odd JSON mapping practices. I can very easily configure a custom Jackson ObjectMapper to handle the mapping, but if I register a Spring MVC message converter with that mapper, it applies the mapping (which is incorrect for the rest of the JSON I'm dealing with) to all incoming requests.

我可以应用一些手动方法来手动解码这些消息,但让 Spring 类型转换服务在请求管道中处理它会更简洁.

There are a handful of manual approaches I can apply to hand-decode these messages, but it would be much cleaner to have the Spring type-conversion service handle it in the request pipeline.

是否有可行的方法将自定义消息转换器附加到特定控制器、处理程序方法或映射字符串/模板/前缀?

Is there a feasible way to attach a custom message converter to a specific controller, handler method, or mapping string/template/prefix?

推荐答案

我遇到了类似的情况 - 我想创建自定义的 @ResponseBody 等效项,以允许我配置 JSON 序列化的某些方面(在我的示例中,我想要 JSON 值可选的 html 编码).我最终创建了自定义的 @JsonResponseBody 注释,这将导致 spring mvc 对用它注释的方法使用不同配置的 Jackson 消息转换器.

I had a similar situation - I wanted to create custom @ResponseBody equivalent that would allow me to configure certain aspects of JSON serialization (in my example, I wanted JSON values optionally html encoded). I ended up creating custom @JsonResponseBodyannotation which would cause spring mvc to use differently configured Jackson message converter for methods annotated with it.

我必须扩展 Spring 的 AbstractMessageConverterMethodProcessor 以注册自定义注释的自定义处理,然后我需要通过将我的 CustomAbstractMessageConverterMethodProcessor 添加到 RequestMappingHandlerAdapter 来使用 Spring 框架注册它 的处理程序列表.这也很棘手,因为如果您使用 xml 配置,则必须通过 BeanPostProcessor 来完成.

I had to extend Spring's AbstractMessageConverterMethodProcessorto register custom handling for my custom annotation and then I needed to register my CustomAbstractMessageConverterMethodProcessor with spring framework by adding it to RequestMappingHandlerAdapter's list of handlers. This was also tricky, because if you use xml config you have to do it via BeanPostProcessor.

在我尝试这个时(一年前,Spring 3.1),我没有找到任何更简单的方法.

At the time I was attempting this (year ago, Spring 3.1), I didn't find any easier way.

这篇关于为单个 Spring Controller 指定消息转换器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆