Spring JMS: how to stop and restart a MDP

Sometimes if you working on system integration may be useful to implement a JMS queue to make asynchronous calls to other applications or software components.

More than one time it happened to me that I needed to stop message consumers of the queue, and later I needed to restart it.

In Java world the message consumer is a MDB (Message Driven Bean), but if you don't want to use an EJB component or if you use every day Spring Framework, you can implement an MDB without EJB.

Spring allows you to create a MDP (Message Driven POJO) through its sub-framework JMSTemplate. All the details to implement a MDP is described in the Spring reference chapter 19.4.2.

In this way MDP is a listener that you can get it from Spring application context and then you can stop it and later you can restart it, as you want ;)

In the following example I'm omitting some of the Spring context configuration that you can see in the reference.

MDP Spring bean definitionMDP Spring bean definition

In the following way you can get and stop a MDP in your business logic method:

How to stop a Spring MDP implemented through a SimpleMessageListenerContainerHow to stop a Spring MDP implemented through a SimpleMessageListenerContainer

The getSpringContext() method can be defined for a Java application and in this case must return an ApplicationContext; otherwise for a Java web application it must return a WebApplicationContext.

In the same way you can get and restart a MDP in your business logic method:

How to restart a Spring MDP implemented through a SimpleMessageListenerContainerHow to restart a Spring MDP implemented through a SimpleMessageListenerContainer