Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set typeIdPropertyName in MappingJackson2MessageConverter

With Spring4 + ActiveMQ I want to receive a JMS Message from a Queue and convert to POJO automatically. I added the MappingJackson2MessageConverter to DefaultJmsListenerContainerFactory:

@Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
    DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();

    // some other config

    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
    converter.setTargetType(MessageType.TEXT);
    converter.setTypeIdPropertyName("???");
    factory.setMessageConverter(converter);

    return factory;
}

And this is my Listener Config

@JmsListener(destination = "queue.fas.flight.order", containerFactory = "jmsListenerContainerFactory")
public void processOrder(OrderRegisterDto registerParam) {
    System.out.println(registerParam.toString());
}

My question is, how do I set TypeIdPropertyName? The Queue is not under my control; others send JSON to it.

I want a common converter so I am using String receive message and am converting it to a POJO manually.

@JmsListener(destination = "xxxx", containerFactory = "xxxxx")
 public void order(String registerParam) {
    try{
        OrderRegisterDto dto = objectMapper.readValue(registerParam,OrderRegisterDto.class);
    }catch (IOException e){
        // TODO
    }
}

Are there any other better methods?

like image 510
Mr.Sheng Avatar asked Apr 06 '16 09:04

Mr.Sheng


1 Answers

The converter expects the sender to provide type information for the conversion in a message property.

String typeId = message.getStringProperty(this.typeIdPropertyName);

The typeId can be a class name, or a key for an entry in the typeId mapping map.

If your message does not contain any type information, you need to subclass the converter and override getJavaTypeForMessage() to return a Jackson JavaType for the target class, e.g.:

return TypeFactory.defaultInstance().constructType(Foo.class);

If it's a constant and not dependent on some information in the message, you can create a static field in your subclass.

like image 106
Gary Russell Avatar answered Sep 18 '22 20:09

Gary Russell