javaspringjmsspring-jms

Spring JmsTemplate - add custom Property


I am using the Spring API's JmsTemplate and MappingJackson2MessageConverter (version: spring-jms-4.3.4.RELEASE.jar) to publish messages to an ActiveMQ topic as shown in the below code.

TopicPublisher class:

@Component
public class TopicPublisher {

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private MessageConverter messageConverter;

    public void send() {
        Product product = new Product();
        product.setName("abcd");
        product.setPrice(10);

        jmsTemplate.setMessageConverter(messageConverter);
        jmsTemplate.convertAndSend("product.topic", product);
    }
}

MappingJackson2MessageConverter class:

@Configuration
public class JMSTextMessageConverter {

    @Bean
    public MessageConverter jacksonJmsMessageConverter() {
        MappingJackson2MessageConverter mappingJackson2MessageConverter 
             = new MappingJackson2MessageConverter();
        mappingJackson2MessageConverter.setTargetType(MessageType.TEXT);
        mappingJackson2MessageConverter.setTypeIdPropertyName("_type");
        return mappingJackson2MessageConverter;
    }   
}

Now, I want to set few custom headers to the JMS message being published to the topic. I googled and could not find any example which does this. Can you help ?


Solution

  • You can add custom properties by using convertAndSendmethod from JmsTemplate by sending MessagePostProcessor as shown below:

    jmsTemplate.convertAndSend("product.topic", product, new MessagePostProcessor() {
                @Override
                public Message postProcessMessage(Message message) throws JMSException {
                    message.setStringProperty("my_property", "my_value");
                    return message;
                }
            });
    

    Alternative lambda syntax:

    jmsTemplate.convertAndSend(
                "product.topic", product,
                message -> { message.setStringProperty("my_property", "my_value"); return message;}
        );