【问题标题】:How can I create a custom converter/deserializer for @Header values in Spring Websocket如何在 Spring Websocket 中为 @Header 值创建自定义转换器/反序列化器
【发布时间】:2021-12-26 12:45:20
【问题描述】:

我有一个 Websocket 端点,我想将其作为标头值接收,而不是字符串而是对象。

这就是我定义 websocket 端点的方式

    @MessageMapping("/gather/{resource}")
    fun emitGatherEvent(@DestinationVariable resource: String, @Header context: Context) {     
        LOG.debug("gather endpoint called for client ${context.clientId} and character ${context.characterId} with resource '$resource'")
        eventDispatcher.dispatchEvent(Gather(resource), context.characterId)
    }

然而 Spring 抛出异常:

org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [@org.springframework.messaging.handler.annotation.Header com.barbarus.gameserver.websocket.Context]

我了解这个问题,但我不知道如何为 Context 数据类注册自定义转换器。

知道怎么做吗?

【问题讨论】:

    标签: java kotlin spring-mvc websocket spring-websocket


    【解决方案1】:

    您可以通过FormatterRegistry 进行此操作

    @Configuration
    public class YourConfig implements WebMvcConfigurer{
     @Override
        public void addFormatters(FormatterRegistry registry) {
         registry.addConverter(new YourCustomConverter());
        }
    }
    

    }

    【讨论】:

    • YourCustomConverter 需要扩展什么类?
    • 例如一个接口Converter
    猜你喜欢
    • 2022-07-21
    • 2018-02-19
    • 2017-09-17
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    • 2015-02-17
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多