2

Spring provides @JMSListener annotation to listen to messages from a particular queue. There is also an alternative to implement JmsListenerConfigurer and register a MessageListener.

In both the cases, the name of the queue has to be known at the time when the application starts, either by hardcoding in the code or via properties.

Is there a way to listen to a queue whose name is known to the application much later after it started?

Sundeep
  • 1,536
  • 5
  • 23
  • 35

1 Answers1

3

This should work.

  1. Configure the @JmsListener with a dummy queue name and an id.
  2. Configure the listener container factory with autoStartup false.
  3. When you are ready, get a reference to the listener container using it's id from the JmsListenerEndpointRegistry (auto wire the registry into your app and call getListenerContainer(id)).
  4. Cast the container to an AbstractMessageListenerContainer and call setDestinationName (or setDestination) with the desired queue.
  5. start() it.
Gary Russell
  • 166,535
  • 14
  • 146
  • 179
  • 1
    If you wish to dynamically create lots of containers, then just create the containers programmatically, call `afterPropertiesSet()`, then `start()`. – Gary Russell Nov 24 '16 at 17:37
  • Thanks a lot! I will try this and update. Would you happen to know how heavy the containers are, compared to the listener objects, in case I happen to have multiple on request queue listeners? – Sundeep Nov 24 '16 at 17:46
  • 1
    I am not sure what you mean; each `@JmsListener` runs in a `DefaultMessageListenerContainer` created by the factory. It's effectively the same as creating the container programmatically and wrapping your POJO listener in a `MessageListenerAdapter`. – Gary Russell Nov 24 '16 at 18:09
  • Ah, thanks for clearing that up. On second thought, I liked the effective way you mentioned in the last comment and ended up creating a container when I have the queue name and then init and start it. It also allows me to attach a message listener, instead of trying to route the message from the `@JMSListener` which is neat too. – Sundeep Nov 24 '16 at 19:00
  • Thanks Gary! Above solution helped me create ContainerFactory and Listeners dynamically. – Amit Kaneria Jun 07 '19 at 15:03