SpringBoot自定义MessageConverter及其源码分析

SpringBoot自定义MessageConverter及其源码分析

正在学习SpringBoot,在自定义MessageConverter时发现:为同一个返回值类型配置多个MessageConverter时,可能会发生响应数据格式错误,或406异常(客户端无法接收相应数据)。在此记录一下解决问题以及追踪源码的过程。此处的讨论场景为:基于请求参数的内容协商,详见需求描述。

一 需求描述

  1. 前提条件:浏览器访问路径为http://localhost:8080/showPerson,服务器端对应的Controller如下:
@RestController
public class ParamController {
   
    @GetMapping("/showPerson")
    public Person showPerson(Person person){
   
        person.setUserName("lisi");
        person.setAge(35);
        return person;
    }
}
  1. 需求:建立两个自定义的MessageConverter,并利用URL请求路径中携带的format参数来控制使用哪个converter。举例来说:

    当发送请求 http://localhost:8080/showPerson?format=something时,需要的响应格式为:lisi - something - 35
    当发送请求 http://localhost:8080/showPerson?format=anything时,需要的响应格式为:lisi - anything - 35

  • PS:用 POST方式请求或许更合理,这里为了省事儿直接用 GET了。

二 最初的实现

  1. 根据上面的需求,我们首先创建了如下的配置类:
@Configuration(proxyBeanMethods = false)
public class WebConfig /*implements WebMvcConfigurer*/ {
   

    //1、WebMvcConfigurer定制化SpringMVC的功能
    @Bean
    public WebMvcConfigurer webMvcConfigurer(){
   
        return new WebMvcConfigurer() {
   
            @Override
            public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
   
				// 创建Map,用于收集MediaType信息
                Map<String, MediaType> mediaTypes = new HashMap<>();
                mediaTypes.put("json",MediaType.APPLICATION_JSON);
                mediaTypes.put("xml",MediaType.APPLICATION_XML);
                // 添加自定义的媒体类型
                mediaTypes.
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
MessageConverter是一个接口,它有两个主要的功能。首先,它可以将Java对象转换为对应的JMS消息。其次,它可以将JMS消息转换为对应的Java对象。在消息监听器接收到JMS消息时,我们可以通过注入一个MessageConverter并调用它的fromMessage方法,将消息转换为Java对象。例如,在ConsumerMessageListener类中,我们可以使用messageConverter.fromMessage(objMessage)将ObjectMessage转换为Email对象。这样,我们就可以方便地处理JMS消息并使用对应的Java对象进行操作。 要定义自己的MessageConverter,只需要实现Spring提供的MessageConverter接口,并实现其中的toMessage和fromMessage方法。toMessage方法用于将Java对象转换为JMS消息,而fromMessage方法用于将JMS消息转换为Java对象。在使用JmsTemplate发送消息时,如果使用了MessageConverter,我们只需要调用convertAndSend方法即可,JmsTemplate会在内部调用预定的MessageConverter来转换消息并发送。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span> #### 引用[.reference_title] - *1* *2* *3* *4* [Spring整合JMS(三)——MessageConverter介绍](https://blog.csdn.net/u010961759/article/details/39293981)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值