Andres
Andres

Reputation: 10727

How to get custom properties from JMS message in a Spring JMS Listener

I know you can access standard headers in a Spring JMS listener with something like this:

public void receive(String in, @Header(JmsHeaders.MESSAGE_ID) String messageId) 

Is there any similar annotation for getting access to custom properties?

Upvotes: 3

Views: 8865

Answers (1)

Gary Russell
Gary Russell

Reputation: 174749

Exactly the same way...

  • Either use @Header annotation (see method listen)

OR

  • Use Message interface which wraps message header and payload (see method listenMessage)
@SpringBootApplication
public class So52891334Application {

    public static void main(String[] args) {
        SpringApplication.run(So52891334Application.class, args);
    }

    @JmsListener(destination = "foo")
    public void listen(String payload, @Header("bar") String bar,
                                       @Header("qux") int qux) {
        System.out.println(payload + ", bar header: " + bar + ", qux header: " + qux);
    }

    @JmsListener(destination = "bar")
    public void listenMessage(Message<String> message) {
        String payload = message.getPayload();

        // Get headers from JMS message
        MessageHeaders headers = message.getHeaders();
        String headerBar = headers.get("bar", String.class);
        Integer headerQux = headers.get("qux", Integer.class);

        System.out.println(payload + ", bar header: " + headerBar + ", qux header: " + headerQux);
    }

    @Bean
    public ApplicationRunner runner(JmsTemplate template) {
        return args -> template.convertAndSend("foo", "test", m -> {
            m.setStringProperty("bar", "baz");
            m.setIntProperty("qux", 42);
            return m;
        });
    }

}

and

test, bar header: baz, qux header: 42

Upvotes: 7

Related Questions