Spring Framework

org.springframework.jms.listener
Class AbstractMessageListenerContainer

java.lang.Object
  extended by org.springframework.jms.support.JmsAccessor
      extended by org.springframework.jms.support.destination.JmsDestinationAccessor
          extended by org.springframework.jms.listener.AbstractJmsListeningContainer
              extended by org.springframework.jms.listener.AbstractMessageListenerContainer
All Implemented Interfaces:
Aware, BeanNameAware, DisposableBean, InitializingBean, Lifecycle, Phased, SmartLifecycle
Direct Known Subclasses:
AbstractPollingMessageListenerContainer, SimpleMessageListenerContainer

public abstract class AbstractMessageListenerContainer
extends AbstractJmsListeningContainer

Abstract base class for message listener containers. Can either host a standard JMS MessageListener or a Spring-specific SessionAwareMessageListener.

Usually holds a single JMS Connection that all listeners are supposed to be registered on, which is the standard JMS way of managing listeners. Can alternatively also be used with a fresh Connection per listener, for J2EE-style XA-aware JMS messaging. The actual registration process is up to concrete subclasses.

NOTE: The default behavior of this message listener container is to never propagate an exception thrown by a message listener up to the JMS provider. Instead, it will log any such exception at the error level. This means that from the perspective of the attendant JMS provider no such listener will ever fail. However, if error handling is necessary, then any implementation of the ErrorHandler strategy may be provided to the setErrorHandler(ErrorHandler) method. Note that JMSExceptions will be passed to the ErrorHandler in addition to (but after) being passed to an ExceptionListener, if one has been provided.

The listener container offers the following message acknowledgment options:

The exact behavior might vary according to the concrete listener container and JMS provider used.

There are two solutions to the duplicate processing problem:

Note that XA transaction coordination adds significant runtime overhead, so it might be feasible to avoid it unless absolutely necessary.

Recommendations:

Note that it is also possible to specify a JmsTransactionManager as external "transactionManager", providing fully synchronized Spring transactions based on local JMS transactions. The effect is similar to "sessionTransacted" set to "true", the difference being that this external transaction management will also affect independent JMS access code within the service layer (e.g. based on JmsTemplate or TransactionAwareConnectionFactoryProxy), not just direct JMS Session usage in a SessionAwareMessageListener.

Since:
2.0
Author:
Juergen Hoeller
See Also:
setMessageListener(java.lang.Object), MessageListener, SessionAwareMessageListener, handleListenerException(java.lang.Throwable), DefaultMessageListenerContainer, SimpleMessageListenerContainer, JmsMessageEndpointManager

Nested Class Summary
 
Nested classes/interfaces inherited from class org.springframework.jms.listener.AbstractJmsListeningContainer
AbstractJmsListeningContainer.SharedConnectionNotInitializedException
 
Field Summary
 
Fields inherited from class org.springframework.jms.listener.AbstractJmsListeningContainer
lifecycleMonitor, sharedConnectionMonitor
 
Fields inherited from class org.springframework.jms.support.JmsAccessor
logger
 
Constructor Summary
AbstractMessageListenerContainer()
           
 
Method Summary
protected  void checkMessageListener(java.lang.Object messageListener)
          Check the given message listener, throwing an exception if it does not correspond to a supported listener type.
protected  void commitIfNecessary(javax.jms.Session session, javax.jms.Message message)
          Perform a commit or message acknowledgement, as appropriate.
protected  void doExecuteListener(javax.jms.Session session, javax.jms.Message message)
          Execute the specified listener, committing or rolling back the transaction afterwards (if necessary).
protected  void doInvokeListener(javax.jms.MessageListener listener, javax.jms.Message message)
          Invoke the specified listener as standard JMS MessageListener.
protected  void doInvokeListener(SessionAwareMessageListener listener, javax.jms.Session session, javax.jms.Message message)
          Invoke the specified listener as Spring SessionAwareMessageListener, exposing a new JMS Session (potentially with its own transaction) to the listener if demanded.
protected  void executeListener(javax.jms.Session session, javax.jms.Message message)
          Execute the specified listener, committing or rolling back the transaction afterwards (if necessary).
protected  java.lang.String getDefaultSubscriptionName(java.lang.Object messageListener)
          Determine the default subscription name for the given message listener.
 javax.jms.Destination getDestination()
          Return the destination to receive messages from.
protected  java.lang.String getDestinationDescription()
          Return a descriptive String for this container's JMS destination (never null).
 java.lang.String getDestinationName()
          Return the name of the destination to receive messages from.
 java.lang.String getDurableSubscriptionName()
          Return the name of a durable subscription to create, if any.
 javax.jms.ExceptionListener getExceptionListener()
          Return the JMS ExceptionListener to notify in case of a JMSException thrown by the registered message listener or the invocation infrastructure, if any.
 java.lang.Object getMessageListener()
          Return the message listener object to register.
 java.lang.String getMessageSelector()
          Return the JMS message selector expression (or null if none).
protected  void handleListenerException(java.lang.Throwable ex)
          Handle the given exception that arose during listener execution.
protected  void invokeErrorHandler(java.lang.Throwable ex)
          Invoke the registered ErrorHandler, if any.
protected  void invokeExceptionListener(javax.jms.JMSException ex)
          Invoke the registered JMS ExceptionListener, if any.
protected  void invokeListener(javax.jms.Session session, javax.jms.Message message)
          Invoke the specified listener: either as standard JMS MessageListener or (preferably) as Spring SessionAwareMessageListener.
 boolean isAcceptMessagesWhileStopping()
          Return whether to accept received messages while the listener container in the process of stopping.
 boolean isExposeListenerSession()
          Return whether to expose the listener JMS Session to a registered SessionAwareMessageListener.
protected  boolean isSessionLocallyTransacted(javax.jms.Session session)
          Check whether the given Session is locally transacted, that is, whether its transaction is managed by this listener container's Session handling and not by an external transaction coordinator.
 boolean isSubscriptionDurable()
          Return whether to make the subscription durable.
protected  void rollbackIfNecessary(javax.jms.Session session)
          Perform a rollback, if appropriate.
protected  void rollbackOnExceptionIfNecessary(javax.jms.Session session, java.lang.Throwable ex)
          Perform a rollback, handling rollback exceptions properly.
 void setAcceptMessagesWhileStopping(boolean acceptMessagesWhileStopping)
          Set whether to accept received messages while the listener container in the process of stopping.
 void setDestination(javax.jms.Destination destination)
          Set the destination to receive messages from.
 void setDestinationName(java.lang.String destinationName)
          Set the name of the destination to receive messages from.
 void setDurableSubscriptionName(java.lang.String durableSubscriptionName)
          Set the name of a durable subscription to create.
 void setErrorHandler(ErrorHandler errorHandler)
          Set an ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message.
 void setExceptionListener(javax.jms.ExceptionListener exceptionListener)
          Set the JMS ExceptionListener to notify in case of a JMSException thrown by the registered message listener or the invocation infrastructure.
 void setExposeListenerSession(boolean exposeListenerSession)
          Set whether to expose the listener JMS Session to a registered SessionAwareMessageListener as well as to JmsTemplate calls.
 void setMessageListener(java.lang.Object messageListener)
          Set the message listener implementation to register.
 void setMessageSelector(java.lang.String messageSelector)
          Set the JMS message selector expression (or null if none).
 void setSubscriptionDurable(boolean subscriptionDurable)
          Set whether to make the subscription durable.
protected  void validateConfiguration()
          Validate the configuration of this container.
 
Methods inherited from class org.springframework.jms.listener.AbstractJmsListeningContainer
afterPropertiesSet, createSharedConnection, destroy, doInitialize, doRescheduleTask, doShutdown, doStart, doStop, establishSharedConnection, getBeanName, getClientId, getPausedTaskCount, getPhase, getSharedConnection, initialize, isActive, isAutoStartup, isRunning, logRejectedTask, prepareSharedConnection, refreshSharedConnection, rescheduleTaskIfNecessary, resumePausedTasks, runningAllowed, setAutoStartup, setBeanName, setClientId, setPhase, sharedConnectionEnabled, shutdown, start, startSharedConnection, stop, stop, stopSharedConnection
 
Methods inherited from class org.springframework.jms.support.destination.JmsDestinationAccessor
getDestinationResolver, isPubSubDomain, resolveDestinationName, setDestinationResolver, setPubSubDomain
 
Methods inherited from class org.springframework.jms.support.JmsAccessor
convertJmsAccessException, createConnection, createSession, getConnectionFactory, getSessionAcknowledgeMode, isClientAcknowledge, isSessionTransacted, setConnectionFactory, setSessionAcknowledgeMode, setSessionAcknowledgeModeName, setSessionTransacted
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

AbstractMessageListenerContainer

public AbstractMessageListenerContainer()
Method Detail

setDestination

public void setDestination(javax.jms.Destination destination)
Set the destination to receive messages from.

Alternatively, specify a "destinationName", to be dynamically resolved via the DestinationResolver.

Note: The destination may be replaced at runtime, with the listener container picking up the new destination immediately (works e.g. with DefaultMessageListenerContainer, as long as the cache level is less than CACHE_CONSUMER). However, this is considered advanced usage; use it with care!

See Also:
setDestinationName(String)

getDestination

public javax.jms.Destination getDestination()
Return the destination to receive messages from. Will be null if the configured destination is not an actual Destination type; c.f. when the destination is a String.


setDestinationName

public void setDestinationName(java.lang.String destinationName)
Set the name of the destination to receive messages from.

The specified name will be dynamically resolved via the configured destination resolver.

Alternatively, specify a JMS Destination object as "destination".

Note: The destination may be replaced at runtime, with the listener container picking up the new destination immediately (works e.g. with DefaultMessageListenerContainer, as long as the cache level is less than CACHE_CONSUMER). However, this is considered advanced usage; use it with care!

Parameters:
destinationName - the desired destination (can be null)
See Also:
setDestination(javax.jms.Destination)

getDestinationName

public java.lang.String getDestinationName()
Return the name of the destination to receive messages from. Will be null if the configured destination is not a String type; c.f. when it is an actual Destination.


getDestinationDescription

protected java.lang.String getDestinationDescription()
Return a descriptive String for this container's JMS destination (never null).


setMessageSelector

public void setMessageSelector(java.lang.String messageSelector)
Set the JMS message selector expression (or null if none). Default is none.

See the JMS specification for a detailed definition of selector expressions.

Note: The message selector may be replaced at runtime, with the listener container picking up the new selector value immediately (works e.g. with DefaultMessageListenerContainer, as long as the cache level is less than CACHE_CONSUMER). However, this is considered advanced usage; use it with care!


getMessageSelector

public java.lang.String getMessageSelector()
Return the JMS message selector expression (or null if none).


setMessageListener

public void setMessageListener(java.lang.Object messageListener)
Set the message listener implementation to register. This can be either a standard JMS MessageListener object or a Spring SessionAwareMessageListener object.

Note: The message listener may be replaced at runtime, with the listener container picking up the new listener object immediately (works e.g. with DefaultMessageListenerContainer, as long as the cache level is less than CACHE_CONSUMER). However, this is considered advanced usage; use it with care!

Throws:
java.lang.IllegalArgumentException - if the supplied listener is not a MessageListener or a SessionAwareMessageListener
See Also:
MessageListener, SessionAwareMessageListener

getMessageListener

public java.lang.Object getMessageListener()
Return the message listener object to register.


checkMessageListener

protected void checkMessageListener(java.lang.Object messageListener)
Check the given message listener, throwing an exception if it does not correspond to a supported listener type.

By default, only a standard JMS MessageListener object or a Spring SessionAwareMessageListener object will be accepted.

Parameters:
messageListener - the message listener object to check
Throws:
java.lang.IllegalArgumentException - if the supplied listener is not a MessageListener or a SessionAwareMessageListener
See Also:
MessageListener, SessionAwareMessageListener

getDefaultSubscriptionName

protected java.lang.String getDefaultSubscriptionName(java.lang.Object messageListener)
Determine the default subscription name for the given message listener.

Parameters:
messageListener - the message listener object to check
Returns:
the default subscription name
See Also:
SubscriptionNameProvider

setSubscriptionDurable

public void setSubscriptionDurable(boolean subscriptionDurable)
Set whether to make the subscription durable. The durable subscription name to be used can be specified through the "durableSubscriptionName" property.

Default is "false". Set this to "true" to register a durable subscription, typically in combination with a "durableSubscriptionName" value (unless your message listener class name is good enough as subscription name).

Only makes sense when listening to a topic (pub-sub domain).

See Also:
setDurableSubscriptionName(java.lang.String)

isSubscriptionDurable

public boolean isSubscriptionDurable()
Return whether to make the subscription durable.


setDurableSubscriptionName

public void setDurableSubscriptionName(java.lang.String durableSubscriptionName)
Set the name of a durable subscription to create. To be applied in case of a topic (pub-sub domain) with subscription durability activated.

The durable subscription name needs to be unique within this client's JMS client id. Default is the class name of the specified message listener.

Note: Only 1 concurrent consumer (which is the default of this message listener container) is allowed for each durable subscription.

See Also:
setSubscriptionDurable(boolean), AbstractJmsListeningContainer.setClientId(java.lang.String), setMessageListener(java.lang.Object)

getDurableSubscriptionName

public java.lang.String getDurableSubscriptionName()
Return the name of a durable subscription to create, if any.


setExceptionListener

public void setExceptionListener(javax.jms.ExceptionListener exceptionListener)
Set the JMS ExceptionListener to notify in case of a JMSException thrown by the registered message listener or the invocation infrastructure.


getExceptionListener

public javax.jms.ExceptionListener getExceptionListener()
Return the JMS ExceptionListener to notify in case of a JMSException thrown by the registered message listener or the invocation infrastructure, if any.


setErrorHandler

public void setErrorHandler(ErrorHandler errorHandler)
Set an ErrorHandler to be invoked in case of any uncaught exceptions thrown while processing a Message. By default there will be no ErrorHandler so that error-level logging is the only result.


setExposeListenerSession

public void setExposeListenerSession(boolean exposeListenerSession)
Set whether to expose the listener JMS Session to a registered SessionAwareMessageListener as well as to JmsTemplate calls.

Default is "true", reusing the listener's Session. Turn this off to expose a fresh JMS Session fetched from the same underlying JMS Connection instead, which might be necessary on some JMS providers.

Note that Sessions managed by an external transaction manager will always get exposed to JmsTemplate calls. So in terms of JmsTemplate exposure, this setting only affects locally transacted Sessions.

See Also:
SessionAwareMessageListener

isExposeListenerSession

public boolean isExposeListenerSession()
Return whether to expose the listener JMS Session to a registered SessionAwareMessageListener.


setAcceptMessagesWhileStopping

public void setAcceptMessagesWhileStopping(boolean acceptMessagesWhileStopping)
Set whether to accept received messages while the listener container in the process of stopping.

Default is "false", rejecting such messages through aborting the receive attempt. Switch this flag on to fully process such messages even in the stopping phase, with the drawback that even newly sent messages might still get processed (if coming in before all receive timeouts have expired).

NOTE: Aborting receive attempts for such incoming messages might lead to the provider's retry count decreasing for the affected messages. If you have a high number of concurrent consumers, make sure that the number of retries is higher than the number of consumers, to be on the safe side for all potential stopping scenarios.


isAcceptMessagesWhileStopping

public boolean isAcceptMessagesWhileStopping()
Return whether to accept received messages while the listener container in the process of stopping.


validateConfiguration

protected void validateConfiguration()
Description copied from class: AbstractJmsListeningContainer
Validate the configuration of this container.

The default implementation is empty. To be overridden in subclasses.

Overrides:
validateConfiguration in class AbstractJmsListeningContainer

executeListener

protected void executeListener(javax.jms.Session session,
                               javax.jms.Message message)
Execute the specified listener, committing or rolling back the transaction afterwards (if necessary).

Parameters:
session - the JMS Session to operate on
message - the received JMS Message
See Also:
invokeListener(javax.jms.Session, javax.jms.Message), commitIfNecessary(javax.jms.Session, javax.jms.Message), rollbackOnExceptionIfNecessary(javax.jms.Session, java.lang.Throwable), handleListenerException(java.lang.Throwable)

doExecuteListener

protected void doExecuteListener(javax.jms.Session session,
                                 javax.jms.Message message)
                          throws javax.jms.JMSException
Execute the specified listener, committing or rolling back the transaction afterwards (if necessary).

Parameters:
session - the JMS Session to operate on
message - the received JMS Message
Throws:
javax.jms.JMSException - if thrown by JMS API methods
See Also:
invokeListener(javax.jms.Session, javax.jms.Message), commitIfNecessary(javax.jms.Session, javax.jms.Message), rollbackOnExceptionIfNecessary(javax.jms.Session, java.lang.Throwable), JmsAccessor.convertJmsAccessException(javax.jms.JMSException)

invokeListener

protected void invokeListener(javax.jms.Session session,
                              javax.jms.Message message)
                       throws javax.jms.JMSException
Invoke the specified listener: either as standard JMS MessageListener or (preferably) as Spring SessionAwareMessageListener.

Parameters:
session - the JMS Session to operate on
message - the received JMS Message
Throws:
javax.jms.JMSException - if thrown by JMS API methods
See Also:
setMessageListener(java.lang.Object)

doInvokeListener

protected void doInvokeListener(SessionAwareMessageListener listener,
                                javax.jms.Session session,
                                javax.jms.Message message)
                         throws javax.jms.JMSException
Invoke the specified listener as Spring SessionAwareMessageListener, exposing a new JMS Session (potentially with its own transaction) to the listener if demanded.

Parameters:
listener - the Spring SessionAwareMessageListener to invoke
session - the JMS Session to operate on
message - the received JMS Message
Throws:
javax.jms.JMSException - if thrown by JMS API methods
See Also:
SessionAwareMessageListener, setExposeListenerSession(boolean)

doInvokeListener

protected void doInvokeListener(javax.jms.MessageListener listener,
                                javax.jms.Message message)
                         throws javax.jms.JMSException
Invoke the specified listener as standard JMS MessageListener.

Default implementation performs a plain invocation of the onMessage method.

Parameters:
listener - the JMS MessageListener to invoke
message - the received JMS Message
Throws:
javax.jms.JMSException - if thrown by JMS API methods
See Also:
MessageListener.onMessage(javax.jms.Message)

commitIfNecessary

protected void commitIfNecessary(javax.jms.Session session,
                                 javax.jms.Message message)
                          throws javax.jms.JMSException
Perform a commit or message acknowledgement, as appropriate.

Parameters:
session - the JMS Session to commit
message - the Message to acknowledge
Throws:
javax.jms.JMSException - in case of commit failure

rollbackIfNecessary

protected void rollbackIfNecessary(javax.jms.Session session)
                            throws javax.jms.JMSException
Perform a rollback, if appropriate.

Parameters:
session - the JMS Session to rollback
Throws:
javax.jms.JMSException - in case of a rollback error

rollbackOnExceptionIfNecessary

protected void rollbackOnExceptionIfNecessary(javax.jms.Session session,
                                              java.lang.Throwable ex)
                                       throws javax.jms.JMSException
Perform a rollback, handling rollback exceptions properly.

Parameters:
session - the JMS Session to rollback
ex - the thrown application exception or error
Throws:
javax.jms.JMSException - in case of a rollback error

isSessionLocallyTransacted

protected boolean isSessionLocallyTransacted(javax.jms.Session session)
Check whether the given Session is locally transacted, that is, whether its transaction is managed by this listener container's Session handling and not by an external transaction coordinator.

Note: The Session's own transacted flag will already have been checked before. This method is about finding out whether the Session's transaction is local or externally coordinated.

Parameters:
session - the Session to check
Returns:
whether the given Session is locally transacted
See Also:
JmsAccessor.isSessionTransacted(), ConnectionFactoryUtils.isSessionTransactional(javax.jms.Session, javax.jms.ConnectionFactory)

handleListenerException

protected void handleListenerException(java.lang.Throwable ex)
Handle the given exception that arose during listener execution.

The default implementation logs the exception at warn level, not propagating it to the JMS provider — assuming that all handling of acknowledgement and/or transactions is done by this listener container. This can be overridden in subclasses.

Parameters:
ex - the exception to handle

invokeExceptionListener

protected void invokeExceptionListener(javax.jms.JMSException ex)
Invoke the registered JMS ExceptionListener, if any.

Parameters:
ex - the exception that arose during JMS processing
See Also:
setExceptionListener(javax.jms.ExceptionListener)

invokeErrorHandler

protected void invokeErrorHandler(java.lang.Throwable ex)
Invoke the registered ErrorHandler, if any. Log at warn level otherwise.

Parameters:
ex - the uncaught error that arose during JMS processing.
See Also:
setErrorHandler(org.springframework.util.ErrorHandler)

Spring Framework