问题描述
鉴于我有IntegrationFlow
和AMQP队列的入站适配器:
@Bean
public IntegrationFlow readMessagesFlow(
ConnectionFactory rabbitConnectionFactory,ObjectMapper jacksonObjectMapper) {
return IntegrationFlows.from(
Amqp.inboundAdapter(rabbitConnectionFactory,QUEUE)
.messageConverter(new Jackson2JsonMessageConverter(jacksonObjectMapper))
)
.log(INFO,AMQP_LOGGER_CATEGORY)
.get();
}
当某个外部系统使用JSON正文发送消息时,我发现它们使用__TypeId__=THEIR_INTERNAL_CLASS
。
我想将JSON主体映射到自己的类。
当前,由于ClassCastException
不可用,它在THEIR_INTERNAL_CLASS
上失败。
如何告诉Jackson2JsonMessageConverter
使用自己的课程?
解决方法
请参阅此转换器方法:
/**
* Set the precedence for evaluating type information in message properties.
* When using {@code @RabbitListener} at the method level,the framework attempts
* to determine the target type for payload conversion from the method signature.
* If so,this type is provided in the
* {@link MessageProperties#getInferredArgumentType() inferredArgumentType}
* message property.
* <p> By default,if the type is concrete (not abstract,not an interface),this will
* be used ahead of type information provided in the {@code __TypeId__} and
* associated headers provided by the sender.
* <p> If you wish to force the use of the {@code __TypeId__} and associated headers
* (such as when the actual type is a subclass of the method argument type),* set the precedence to {@link Jackson2JavaTypeMapper.TypePrecedence#TYPE_ID}.
* @param typePrecedence the precedence.
* @see DefaultJackson2JavaTypeMapper#setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence)
*/
public void setTypePrecedence(Jackson2JavaTypeMapper.TypePrecedence typePrecedence) {
这是此事的文档:https://docs.spring.io/spring-amqp/docs/2.2.11.RELEASE/reference/html/#json-message-converter
,这是一种方法:
Jackson2JsonMessageConverter messageConverter = new Jackson2JsonMessageConverter(jacksonObjectMapper);
DefaultClassMapper defaultClassMapper = new DefaultClassMapper();
defaultClassMapper.setDefaultType(MyOwnClass.class);
messageConverter.setClassMapper(defaultClassMapper);
并在messageConverter
中使用Amqp.inboundAdapter