jms.xml 62.5 KB
Newer Older
1
<?xml version="1.0" encoding="UTF-8"?>
2 3 4 5
<chapter xmlns="http://docbook.org/ns/docbook" version="5.0"
    xmlns:xlink="http://www.w3.org/1999/xlink"
    xmlns:xi="http://www.w3.org/2001/XInclude"
    xml:id="jms">
6 7 8 9 10 11
  <title>JMS (Java Message Service)</title>

  <section id="jms-introduction">
    <title>Introduction</title>

    <para>Spring provides a JMS integration framework that simplifies the use
M
Mark Pollack 已提交
12 13
    of the JMS API much like Spring's integration does for the JDBC
    API.</para>
14

M
Mark Pollack 已提交
15 16 17 18
    <para>JMS can be roughly divided into two areas of functionality, namely
    the production and consumption of messages. The
    <classname>JmsTemplate</classname> class is used for message production
    and synchronous message reception. For asynchronous reception similar to
T
Thomas Risberg 已提交
19
    Java EE's message-driven bean style, Spring provides a number of message
M
Mark Pollack 已提交
20 21
    listener containers that are used to create Message-Driven POJOs
    (MDPs).</para>
22 23 24

    <para>The package <literal>org.springframework.jms.core</literal> provides
    the core functionality for using JMS. It contains JMS template classes
25
    that simplify the use of the JMS by handling the creation and release of
26 27 28 29 30 31 32 33 34 35
    resources, much like the <classname>JdbcTemplate</classname> does for
    JDBC. The design principle common to Spring template classes is to provide
    helper methods to perform common operations and for more sophisticated
    usage, delegate the essence of the processing task to user implemented
    callback interfaces. The JMS template follows the same design. The classes
    offer various convenience methods for the sending of messages, consuming a
    message synchronously, and exposing the JMS session and message producer
    to the user.</para>

    <para>The package <literal>org.springframework.jms.support</literal>
M
Mark Pollack 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49
    provides <classname>JMSException</classname> translation functionality.
    The translation converts the checked <classname>JMSException</classname>
    hierarchy to a mirrored hierarchy of unchecked exceptions. If there are
    any provider specific subclasses of the checked
    <classname>javax.jms.JMSException</classname>, this exception is wrapped
    in the unchecked <classname>UncategorizedJmsException</classname>.</para>

    <para>The package
    <literal>org.springframework.jms.support.converter</literal> provides a
    <interfacename>MessageConverter</interfacename> abstraction to convert
    between Java objects and JMS messages.</para>

    <para>The package
    <literal>org.springframework.jms.support.destination</literal> provides
50 51 52 53 54 55 56
    various strategies for managing JMS destinations, such as providing a
    service locator for destinations stored in JNDI.</para>

    <para>Finally, the package
    <literal>org.springframework.jms.connection</literal> provides an
    implementation of the <classname>ConnectionFactory</classname> suitable
    for use in standalone applications. It also contains an implementation of
M
Mark Pollack 已提交
57 58 59
    Spring's <interfacename>PlatformTransactionManager</interfacename> for JMS
    (the cunningly named <classname>JmsTransactionManager</classname>). This
    allows for seamless integration of JMS as a transactional resource into
60 61
    Spring's transaction management mechanisms.</para>
  </section>
M
Mark Pollack 已提交
62

63
  <section id="jms-using">
M
Mark Pollack 已提交
64 65 66 67 68 69 70 71
    <title>Using Spring JMS</title>

    <section id="jms-jmstemplate">
      <title><classname>JmsTemplate</classname></title>

      <para>The <classname>JmsTemplate</classname> class is the central class
      in the JMS core package. It simplifies the use of JMS since it handles
      the creation and release of resources when sending or synchronously
72
      receiving messages.</para>
M
Mark Pollack 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133

      <para>Code that uses the <classname>JmsTemplate</classname> only needs
      to implement callback interfaces giving them a clearly defined high
      level contract. The <classname>MessageCreator</classname> callback
      interface creates a message given a
      <interfacename>Session</interfacename> provided by the calling code in
      <classname>JmsTemplate</classname>. In order to allow for more complex
      usage of the JMS API, the callback
      <classname>SessionCallback</classname> provides the user with the JMS
      session and the callback <classname>ProducerCallback</classname> exposes
      a <interfacename>Session</interfacename> and
      <interfacename>MessageProducer</interfacename> pair.</para>

      <para>The JMS API exposes two types of send methods, one that takes
      delivery mode, priority, and time-to-live as Quality of Service (QOS)
      parameters and one that takes no QOS parameters which uses default
      values. Since there are many send methods in
      <classname>JmsTemplate</classname>, the setting of the QOS parameters
      have been exposed as bean properties to avoid duplication in the number
      of send methods. Similarly, the timeout value for synchronous receive
      calls is set using the property
      <classname>setReceiveTimeout</classname>.</para>

      <para>Some JMS providers allow the setting of default QOS values
      administratively through the configuration of the ConnectionFactory.
      This has the effect that a call to
      <classname>MessageProducer</classname>'s send method
      <methodname>send(Destination destination, Message message)</methodname>
      will use different QOS default values than those specified in the JMS
      specification. In order to provide consistent management of QOS values,
      the <classname>JmsTemplate</classname> must therefore be specifically
      enabled to use its own QOS values by setting the boolean property
      <property>isExplicitQosEnabled</property> to
      <literal>true</literal>.</para>

      <note>
        <para>Instances of the <classname>JmsTemplate</classname> class are
        <emphasis>thread-safe once configured</emphasis>. This is important
        because it means that you can configure a single instance of a
        <classname>JmsTemplate</classname> and then safely inject this
        <emphasis>shared</emphasis> reference into multiple collaborators. To
        be clear, the <classname>JmsTemplate</classname> is stateful, in that
        it maintains a reference to a
        <interfacename>ConnectionFactory</interfacename>, but this state is
        <emphasis>not</emphasis> conversational state.</para>
      </note>
    </section>

    <section id="jms-connections">
      <title>Connections</title>

      <para>The <classname>JmsTemplate</classname> requires a reference to a
      <classname>ConnectionFactory</classname>. The
      <classname>ConnectionFactory</classname> is part of the JMS
      specification and serves as the entry point for working with JMS. It is
      used by the client application as a factory to create connections with
      the JMS provider and encapsulates various configuration parameters, many
      of which are vendor specific such as SSL configuration options.</para>

      <para>When using JMS inside an EJB, the vendor provides implementations
      of the JMS interfaces so that they can participate in declarative
134 135 136
      transaction management and perform pooling of connections and sessions.
      In order to use this implementation, Java EE containers typically
      require that you declare a JMS connection factory as a
M
Mark Pollack 已提交
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
      <property>resource-ref</property> inside the EJB or servlet deployment
      descriptors. To ensure the use of these features with the
      <classname>JmsTemplate</classname> inside an EJB, the client application
      should ensure that it references the managed implementation of the
      <classname>ConnectionFactory</classname>.</para>

      <section>
        <title>Caching Messaging Resources</title>

        <para>The standard API involves creating many intermediate objects. To
        send a message the following 'API' walk is performed</para>

        <programlisting>ConnectionFactory-&gt;Connection-&gt;Session-&gt;MessageProducer-&gt;send</programlisting>

        <para>Between the ConnectionFactory and the Send operation there are
        three intermediate objects that are created and destroyed. To optimise
        the resource usage and increase performance two implementations of
        IConnectionFactory are provided.</para>
      </section>

      <section>
        <title>SingleConnectionFactory</title>

        <para>Spring provides an implementation of the
        <classname>ConnectionFactory</classname> interface,
        <classname>SingleConnectionFactory</classname>, that will return the
        same <classname>Connection</classname> on all
164 165
        <methodname>createConnection()</methodname> calls and ignore calls to
        <methodname>close()</methodname>. This is useful for testing and
M
Mark Pollack 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        standalone environments so that the same connection can be used for
        multiple <classname>JmsTemplate</classname> calls that may span any
        number of transactions. <classname>SingleConnectionFactory</classname>
        takes a reference to a standard
        <classname>ConnectionFactory</classname> that would typically come
        from JNDI.</para>
      </section>

      <section>
        <title>CachingConnectionFactory</title>

        <para>The <classname>CachingConnectionFactory</classname> extends the
        functionality of <classname>SingleConnectionFactory</classname> and
        adds the caching of Sessions, MessageProducers, and MessageConsumers.
        The initial cache size is set to 1, use the property
        <property>SessionCacheSize</property> to increase the number of cached
        sessions. Note that the number of actual cached sessions will be more
        than that number as sessions are cached based on their acknowledgment
        mode, so there can be up to 4 cached session instances when
        <property>SessionCacheSize</property> is set to one, one for each
        AcknowledgementMode. MessageProducers and MessageConsumers are cached
        within their owning session and also take into account the unique
        properties of the producers and consumers when caching.
        MessageProducers are cached based on their destination.
        MessageConsumers are cached based on a key composed of the
        destination, selector, noLocal delivery flag, and the durable
        subscription name (if creating durable consumers).</para>
      </section>
    </section>

    <section id="jms-destinations">
      <title>Destination Management</title>

      <para>Destinations, like ConnectionFactories, are JMS administered
      objects that can be stored and retrieved in JNDI. When configuring a
      Spring application context you can use the JNDI factory class
202 203
      <classname>JndiObjectFactoryBean</classname> /
      <literal>&lt;jee:jndi-lookup&gt;</literal> to perform dependency
M
Mark Pollack 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
      injection on your object's references to JMS destinations. However,
      often this strategy is cumbersome if there are a large number of
      destinations in the application or if there are advanced destination
      management features unique to the JMS provider. Examples of such
      advanced destination management would be the creation of dynamic
      destinations or support for a hierarchical namespace of destinations.
      The <classname>JmsTemplate</classname> delegates the resolution of a
      destination name to a JMS destination object to an implementation of the
      interface <classname>DestinationResolver</classname>.
      <classname>DynamicDestinationResolver</classname> is the default
      implementation used by <classname>JmsTemplate</classname> and
      accommodates resolving dynamic destinations. A
      <classname>JndiDestinationResolver</classname> is also provided that
      acts as a service locator for destinations contained in JNDI and
      optionally falls back to the behavior contained in
      <classname>DynamicDestinationResolver</classname>.</para>

      <para>Quite often the destinations used in a JMS application are only
      known at runtime and therefore cannot be administratively created when
      the application is deployed. This is often because there is shared
      application logic between interacting system components that create
      destinations at runtime according to a well-known naming convention.
226
      Even though the creation of dynamic destinations is not part of the JMS
M
Mark Pollack 已提交
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
      specification, most vendors have provided this functionality. Dynamic
      destinations are created with a name defined by the user which
      differentiates them from temporary destinations and are often not
      registered in JNDI. The API used to create dynamic destinations varies
      from provider to provider since the properties associated with the
      destination are vendor specific. However, a simple implementation choice
      that is sometimes made by vendors is to disregard the warnings in the
      JMS specification and to use the <classname>TopicSession</classname>
      method <methodname>createTopic(String topicName)</methodname> or the
      <classname>QueueSession</classname> method
      <methodname>createQueue(String queueName)</methodname> to create a new
      destination with default destination properties. Depending on the vendor
      implementation, <classname>DynamicDestinationResolver</classname> may
      then also create a physical destination instead of only resolving
      one.</para>

      <para>The boolean property <property>pubSubDomain</property> is used to
      configure the <classname>JmsTemplate</classname> with knowledge of what
      JMS domain is being used. By default the value of this property is
      false, indicating that the point-to-point domain, Queues, will be used.
247 248 249
      This property used by <classname>JmsTemplate</classname> determines the
      behavior of dynamic destination resolution via implementations of the
      <interfacename>DestinationResolver</interfacename> interface.</para>
M
Mark Pollack 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263

      <para>You can also configure the <classname>JmsTemplate</classname> with
      a default destination via the property
      <property>defaultDestination</property>. The default destination will be
      used with send and receive operations that do not refer to a specific
      destination.</para>
    </section>

    <section id="jms-mdp">
      <title>Message Listener Containers</title>

      <para>One of the most common uses of JMS messages in the EJB world is to
      drive message-driven beans (MDBs). Spring offers a solution to create
      message-driven POJOs (MDPs) in a way that does not tie a user to an EJB
264 265
      container. (See <xref linkend="jms-asynchronousMessageReception" />
      for detailed coverage of Spring's MDP support.)</para>
M
Mark Pollack 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278

      <para>A message listener container is used to receive messages from a
      JMS message queue and drive the MessageListener that is injected into
      it. The listener container is responsible for all threading of message
      reception and dispatches into the listener for processing. A message
      listener container is the intermediary between an MDP and a messaging
      provider, and takes care of registering to receive messages,
      participating in transactions, resource acquisition and release,
      exception conversion and suchlike. This allows you as an application
      developer to write the (possibly complex) business logic associated with
      receiving a message (and possibly responding to it), and delegates
      boilerplate JMS infrastructure concerns to the framework.</para>

279
      <para>There are two standard JMS message listener containers packaged
M
Mark Pollack 已提交
280 281 282 283 284
      with Spring, each with its specialised feature set.</para>

      <section id="jms-mdp-simple">
        <title>SimpleMessageListenerContainer</title>

285 286 287
        <para>This message listener container is the simpler of the two
        standard flavors. It creates a fixed number of JMS sessions and
        consumers at startup, registers the listener using the standard JMS
288
        <methodname>MessageConsumer.setMessageListener()</methodname> method,
289 290 291 292 293
        and leaves it up the JMS provider to perform listener callbacks.
        This variant does not allow for dynamic adaption to runtime demands or
        for participation in externally managed transactions. Compatibility-wise,
        it stays very close to the spirit of the standalone JMS specification
        - but is generally not compatible with Java EE's JMS restrictions.</para>
M
Mark Pollack 已提交
294 295 296 297 298 299 300 301 302
      </section>

      <section id="jms-mdp-default">
        <title>DefaultMessageListenerContainer</title>

        <para>This message listener container is the one used in most cases.
        In contrast to <classname>SimpleMessageListenerContainer</classname>,
        this container variant does allow for dynamic adaption to runtime
        demands and is able to participate in externally managed transactions.
303
        Each received message is registered with an XA transaction when
304 305 306 307
        configured with a <classname>JtaTransactionManager</classname>; so
        processing may take advantage of XA transaction semantics. This
        listener container strikes a good balance between low requirements on
        the JMS provider, advanced functionality such as transaction
308
        participation, and compatibility with Java EE environments.</para>
M
Mark Pollack 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
      </section>
    </section>

    <section id="jms-tx">
      <title>Transaction management</title>

      <para>Spring provides a <classname>JmsTransactionManager</classname>
      that manages transactions for a single JMS
      <classname>ConnectionFactory</classname>. This allows JMS applications
      to leverage the managed transaction features of Spring as described in
      <xref linkend="transaction" />. The
      <classname>JmsTransactionManager</classname> performs local resource
      transactions, binding a JMS Connection/Session pair from the specified
      <classname>ConnectionFactory</classname> to the thread.
      <classname>JmsTemplate</classname> automatically detects such
      transactional resources and operates on them accordingly.</para>

T
Thomas Risberg 已提交
326
      <para>In a Java EE environment, the
M
Mark Pollack 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339 340
      <classname>ConnectionFactory</classname> will pool Connections and
      Sessions, so those resources are efficiently reused across transactions.
      In a standalone environment, using Spring's
      <classname>SingleConnectionFactory</classname> will result in a shared
      JMS <classname>Connection</classname>, with each transaction having its
      own independent <classname>Session</classname>. Alternatively, consider
      the use of a provider-specific pooling adapter such as ActiveMQ's
      <classname>PooledConnectionFactory</classname> class.</para>

      <para><classname>JmsTemplate</classname> can also be used with the
      <classname>JtaTransactionManager</classname> and an XA-capable JMS
      <classname>ConnectionFactory</classname> for performing distributed
      transactions. Note that this requires the use of a JTA transaction
      manager as well as a properly XA-configured ConnectionFactory! (Check
T
Thomas Risberg 已提交
341
      your Java EE server's / JMS provider's documentation.)</para>
M
Mark Pollack 已提交
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358

      <para>Reusing code across a managed and unmanaged transactional
      environment can be confusing when using the JMS API to create a
      <classname>Session</classname> from a <classname>Connection</classname>.
      This is because the JMS API has only one factory method to create a
      <classname>Session</classname> and it requires values for the
      transaction and acknowledgement modes. In a managed environment, setting
      these values is the responsibility of the environment's transactional
      infrastructure, so these values are ignored by the vendor's wrapper to
      the JMS Connection. When using the <classname>JmsTemplate</classname> in
      an unmanaged environment you can specify these values through the use of
      the properties <literal>sessionTransacted</literal> and
      <literal>sessionAcknowledgeMode</literal>. When using a
      <classname>PlatformTransactionManager</classname> with
      <classname>JmsTemplate</classname>, the template will always be given a
      transactional JMS <classname>Session</classname>.</para>
    </section>
359 360 361
  </section>

  <section id="jms-sending">
M
Mark Pollack 已提交
362 363 364
    <title>Sending a <interfacename>Message</interfacename></title>

    <para>The <classname>JmsTemplate</classname> contains many convenience
365 366 367 368 369 370 371
    methods to send a message. There are send methods that specify the
    destination using a <classname>javax.jms.Destination</classname> object
    and those that specify the destination using a string for use in a JNDI
    lookup. The send method that takes no destination argument uses the
    default destination. Here is an example that sends a message to a queue
    using the 1.0.2 implementation.</para>

M
Mark Pollack 已提交
372
    <programlisting language="java">import javax.jms.ConnectionFactory;
373 374 375 376 377 378 379 380 381 382 383 384 385 386
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.Session;

import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.core.JmsTemplate;

public class JmsQueueSender {

    private JmsTemplate jmsTemplate;
    private Queue queue;

    public void setConnectionFactory(ConnectionFactory cf) {
387
        this.jmsTemplate = new JmsTemplate(cf);
388 389 390 391 392 393 394 395 396 397 398 399 400
    }

    public void setQueue(Queue queue) {
        this.queue = queue;
    }

    public void simpleSend() {
        this.jmsTemplate.send(this.queue, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
              return session.createTextMessage("hello queue world");
            }
        });
    }
M
Mark Pollack 已提交
401 402 403 404
}</programlisting>

    <para>This example uses the <classname>MessageCreator</classname> callback
    to create a text message from the supplied <classname>Session</classname>
405 406
    object. The <classname>JmsTemplate</classname> is constructed by passing a
    reference to a <classname>ConnectionFactory</classname>. As an alternative,
C
Chris Beams 已提交
407
    a zero argument constructor and <property>connectionFactory</property>
408
    is provided and can be used for constructing the instance in JavaBean style
M
Mark Pollack 已提交
409
    (using a BeanFactory or plain Java code). Alternatively, consider deriving
410 411
    from Spring's <classname>JmsGatewaySupport</classname> convenience base class,
    which provides pre-built bean properties for JMS configuration.</para>
412 413

    <para>The method <methodname>send(String destinationName, MessageCreator
C
Chris Beams 已提交
414
    creator)</methodname> lets you send a message using the string name of
M
Mark Pollack 已提交
415 416 417 418 419 420
    the destination. If these names are registered in JNDI, you should set the
    <property>destinationResolver</property> property of the template to an
    instance of <classname>JndiDestinationResolver</classname>.</para>

    <para>If you created the <classname>JmsTemplate</classname> and specified
    a default destination, the <methodname>send(MessageCreator c)</methodname>
421
    sends a message to that destination.</para>
M
Mark Pollack 已提交
422 423 424 425 426

    <section id="jms-msg-conversion">
      <title>Using Message Converters</title>

      <para>In order to facilitate the sending of domain model objects, the
427 428
      <classname>JmsTemplate</classname> has various send methods that take a
      Java object as an argument for a message's data content. The overloaded
429 430
      methods <methodname>convertAndSend()</methodname> and
      <methodname>receiveAndConvert()</methodname> in
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
      <classname>JmsTemplate</classname> delegate the conversion process to an
      instance of the <literal>MessageConverter</literal> interface. This
      interface defines a simple contract to convert between Java objects and
      JMS messages. The default implementation
      <classname>SimpleMessageConverter</classname> supports conversion
      between <classname>String</classname> and
      <classname>TextMessage</classname>, <classname>byte[]</classname> and
      <classname>BytesMesssage</classname>, and
      <classname>java.util.Map</classname> and
      <classname>MapMessage</classname>. By using the converter, you and your
      application code can focus on the business object that is being sent or
      received via JMS and not be concerned with the details of how it is
      represented as a JMS message.</para>

      <para>The sandbox currently includes a
      <classname>MapMessageConverter</classname> which uses reflection to
      convert between a JavaBean and a <classname>MapMessage</classname>.
C
Chris Beams 已提交
448
      Other popular implementation choices you might implement yourself are
449 450
      Converters that use an existing XML marshalling package, such as JAXB,
      Castor, XMLBeans, or XStream, to create a
M
Mark Pollack 已提交
451 452
      <interfacename>TextMessage</interfacename> representing the
      object.</para>
453 454 455

      <para>To accommodate the setting of a message's properties, headers, and
      body that can not be generically encapsulated inside a converter class,
M
Mark Pollack 已提交
456 457 458 459 460
      the <interfacename>MessagePostProcessor</interfacename> interface gives
      you access to the message after it has been converted, but before it is
      sent. The example below demonstrates how to modify a message header and
      a property after a <interfacename>java.util.Map</interfacename> is
      converted to a message.</para>
461

M
Mark Pollack 已提交
462
      <programlisting language="java">public void sendWithConversion() {
463 464 465 466 467 468 469 470 471 472
    Map map = new HashMap();
    map.put("Name", "Mark");
    map.put("Age", new Integer(47));
    jmsTemplate.convertAndSend("testQueue", map, new MessagePostProcessor() {
        public Message postProcessMessage(Message message) throws JMSException {
            message.setIntProperty("AccountID", 1234);
            message.setJMSCorrelationID("123-00001");
            return message;
        }
    });
M
Mark Pollack 已提交
473 474
}</programlisting>

475
      <para>This results in a message of the form:</para>
M
Mark Pollack 已提交
476 477

      <programlisting>MapMessage={
478 479 480 481 482 483 484 485 486 487 488
    Header={
        ... standard headers ...
        CorrelationID={123-00001}
    }
    Properties={
        AccountID={Integer:1234}
    }
    Fields={
        Name={String:Mark}
        Age={Integer:47}
    } 
M
Mark Pollack 已提交
489 490
}</programlisting>
    </section>
491

M
Mark Pollack 已提交
492 493 494 495 496
    <section id="jms-callbacks">
      <title><interfacename>SessionCallback</interfacename> and
      <interfacename>ProducerCallback</interfacename></title>

      <para>While the send operations cover many common usage scenarios, there
497 498 499 500 501 502
      are cases when you want to perform multiple operations on a JMS
      <interfacename>Session</interfacename> or
      <interfacename>MessageProducer</interfacename>. The
      <interfacename>SessionCallback</interfacename> and
      <interfacename>ProducerCallback</interfacename> expose the JMS
      <interfacename>Session</interfacename> and
M
Mark Pollack 已提交
503
      <interfacename>Session</interfacename> /
C
Chris Beams 已提交
504
      <interfacename>MessageProducer</interfacename> pair respectively. The
M
Mark Pollack 已提交
505
      <methodname>execute()</methodname> methods on
506 507
      <classname>JmsTemplate</classname> execute these callback
      methods.</para>
M
Mark Pollack 已提交
508
    </section>
509 510 511
  </section>

  <section id="jms-receiving">
M
Mark Pollack 已提交
512
    <title>Receiving a message</title>
513

M
Mark Pollack 已提交
514 515
    <section id="jms-receiving-sync">
      <title>Synchronous Reception</title>
516

M
Mark Pollack 已提交
517
      <para>While JMS is typically associated with asynchronous processing, it
518 519 520 521 522 523 524
      is possible to consume messages synchronously. The overloaded
      <methodname>receive(..)</methodname> methods provide this functionality.
      During a synchronous receive, the calling thread blocks until a message
      becomes available. This can be a dangerous operation since the calling
      thread can potentially be blocked indefinitely. The property
      <property>receiveTimeout</property> specifies how long the receiver
      should wait before giving up waiting for a message.</para>
M
Mark Pollack 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542
    </section>

    <section id="jms-asynchronousMessageReception">
      <title>Asynchronous Reception - Message-Driven POJOs</title>

      <para>In a fashion similar to a Message-Driven Bean (MDB) in the EJB
      world, the Message-Driven POJO (MDP) acts as a receiver for JMS
      messages. The one restriction (but see also below for the discussion of
      the <classname>MessageListenerAdapter</classname> class) on an MDP is
      that it must implement the
      <interfacename>javax.jms.MessageListener</interfacename> interface.
      Please also be aware that in the case where your POJO will be receiving
      messages on multiple threads, it is important to ensure that your
      implementation is thread-safe.</para>

      <para>Below is a simple implementation of an MDP:</para>

      <programlisting language="java">import javax.jms.JMSException;
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class ExampleListener implements MessageListener {

    public void onMessage(Message message) {
        if (message instanceof TextMessage) {
            try {
                System.out.println(((TextMessage) message).getText());
            }
            catch (JMSException ex) {
                throw new RuntimeException(ex);
            }
        }
        else {
            throw new IllegalArgumentException("Message must be of type TextMessage");
        }
    }
M
Mark Pollack 已提交
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
}</programlisting>

      <para>Once you've implemented your
      <interfacename>MessageListener</interfacename>, it's time to create a
      message listener container.</para>

      <para>Find below an example of how to define and configure one of the
      message listener containers that ships with Spring (in this case the
      <classname>DefaultMessageListenerContainer</classname>).</para>

      <programlisting language="xml"><lineannotation>&lt;!-- this is the Message Driven POJO (MDP) --&gt;</lineannotation>
&lt;bean id="messageListener" class="jmsexample.ExampleListener" /&gt;

<lineannotation>&lt;!-- and this is the message listener container --&gt;</lineannotation>
&lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&gt;
    &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
    &lt;property name="destination" ref="destination"/&gt;
    <emphasis role="bold">&lt;property name="messageListener" ref="messageListener" /&gt;</emphasis>
&lt;/bean&gt;</programlisting>

      <para>Please refer to the Spring Javadoc of the various message listener
      containers for a full description of the features supported by each
      implementation.</para>
    </section>

    <section id="jms-receiving-async-session-aware-message-listener">
      <title>The <interfacename>SessionAwareMessageListener</interfacename>
      interface</title>

      <para>The <interfacename>SessionAwareMessageListener</interfacename>
      interface is a Spring-specific interface that provides a similar
C
Chris Beams 已提交
593
      contract to the JMS <interfacename>MessageListener</interfacename>
M
Mark Pollack 已提交
594 595 596 597 598
      interface, but also provides the message handling method with access to
      the JMS <interfacename>Session</interfacename> from which the
      <interfacename>Message</interfacename> was received.</para>

      <programlisting language="java">package org.springframework.jms.listener;
599 600 601

public interface SessionAwareMessageListener {

M
Mark Pollack 已提交
602 603 604 605 606 607 608 609 610
    void onMessage(Message message, Session session) <emphasis role="bold">throws JMSException</emphasis>;
}</programlisting>

      <para>You can choose to have your MDPs implement this interface (in
      preference to the standard JMS
      <interfacename>MessageListener</interfacename> interface) if you want
      your MDPs to be able to respond to any received messages (using the
      <interfacename>Session</interfacename> supplied in the
      <literal>onMessage(Message, Session)</literal> method). All of the
611
      message listener container implementations that ship with Spring have
M
Mark Pollack 已提交
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
      support for MDPs that implement either the
      <interfacename>MessageListener</interfacename> or
      <interfacename>SessionAwareMessageListener</interfacename> interface.
      Classes that implement the
      <interfacename>SessionAwareMessageListener</interfacename> come with the
      caveat that they are then tied to Spring through the interface. The
      choice of whether or not to use it is left entirely up to you as an
      application developer or architect.</para>

      <para>Please note that the <literal>'onMessage(..)'</literal> method of
      the <interfacename>SessionAwareMessageListener</interfacename> interface
      throws <classname>JMSException</classname>. In contrast to the standard
      JMS <interfacename>MessageListener</interfacename> interface, when using
      the <interfacename>SessionAwareMessageListener</interfacename>
      interface, it is the responsibility of the client code to handle any
      exceptions thrown.</para>
    </section>

    <section id="jms-receiving-async-message-listener-adapter">
      <title>The <classname>MessageListenerAdapter</classname></title>

      <para>The <classname>MessageListenerAdapter</classname> class is the
      final component in Spring's asynchronous messaging support: in a
      nutshell, it allows you to expose almost <emphasis>any</emphasis> class
      as a MDP (there are of course some constraints).</para>

      <para>Consider the following interface definition. Notice that although
      the interface extends neither the
      <interfacename>MessageListener</interfacename> nor
      <interfacename>SessionAwareMessageListener</interfacename> interfaces,
      it can still be used as a MDP via the use of the
      <classname>MessageListenerAdapter</classname> class. Notice also how the
      various message handling methods are strongly typed according to the
      <emphasis>contents</emphasis> of the various
      <interfacename>Message</interfacename> types that they can receive and
      handle.</para>

      <programlisting language="java">public interface MessageDelegate {
650 651 652 653 654 655 656 657

    void handleMessage(String message);

    void handleMessage(Map message);

    void handleMessage(byte[] message);

    void handleMessage(Serializable message);
M
Mark Pollack 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
}</programlisting>

      <programlisting language="java">public class DefaultMessageDelegate implements MessageDelegate {
    <lineannotation>// implementation elided for clarity...</lineannotation>
}</programlisting>

      <para>In particular, note how the above implementation of the
      <interfacename>MessageDelegate</interfacename> interface (the above
      <classname>DefaultMessageDelegate</classname> class) has
      <emphasis>no</emphasis> JMS dependencies at all. It truly is a POJO that
      we will make into an MDP via the following configuration.</para>

      <programlisting language="xml"><lineannotation>&lt;!-- this is the Message Driven POJO (MDP) --&gt;</lineannotation>
<emphasis role="bold">&lt;bean id="messageListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter"&gt;
    &lt;constructor-arg&gt;
        &lt;bean class="jmsexample.DefaultMessageDelegate"/&gt;
    &lt;/constructor-arg&gt;
&lt;/bean&gt;</emphasis>

<lineannotation>&lt;!-- and this is the message listener container... --&gt;</lineannotation>
&lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&gt;
    &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
    &lt;property name="destination" ref="destination"/&gt;
    <emphasis role="bold">&lt;property name="messageListener" ref="messageListener" /&gt;</emphasis>
&lt;/bean&gt;</programlisting>

      <para>Below is an example of another MDP that can only handle the
      receiving of JMS <interfacename>TextMessage</interfacename> messages.
      Notice how the message handling method is actually called
      <literal>'receive'</literal> (the name of the message handling method in
      a <classname>MessageListenerAdapter</classname> defaults to
      <literal>'handleMessage'</literal>), but it is configurable (as you will
      see below). Notice also how the <literal>'receive(..)'</literal> method
      is strongly typed to receive and respond only to JMS
      <interfacename>TextMessage</interfacename> messages.</para>

      <programlisting language="java">public interface TextMessageDelegate {
695 696

    void receive(TextMessage message);
M
Mark Pollack 已提交
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
}</programlisting>

      <programlisting language="java">public class DefaultTextMessageDelegate implements TextMessageDelegate {
    <lineannotation>// implementation elided for clarity...</lineannotation>
}</programlisting>

      <para>The configuration of the attendant
      <classname>MessageListenerAdapter</classname> would look like
      this:</para>

      <programlisting language="xml">&lt;bean id="messageListener" class="org.springframework.jms.listener.adapter.MessageListenerAdapter"&gt;
    &lt;constructor-arg&gt;
        &lt;bean class="jmsexample.DefaultTextMessageDelegate"/&gt;
    &lt;/constructor-arg&gt;
    &lt;property name="defaultListenerMethod" value="receive"/&gt;
    <lineannotation>&lt;!-- we <emphasis role="bold">don't</emphasis> want automatic message context extraction --&gt;</lineannotation>
    &lt;property name="messageConverter"&gt;
        &lt;null/&gt;
    &lt;/property&gt;
&lt;/bean&gt;</programlisting>

      <para>Please note that if the above <literal>'messageListener'</literal>
      receives a JMS <interfacename>Message</interfacename> of a type other
      than <interfacename>TextMessage</interfacename>, an
      <classname>IllegalStateException</classname> will be thrown (and
      subsequently swallowed). Another of the capabilities of the
      <classname>MessageListenerAdapter</classname> class is the ability to
      automatically send back a response
      <interfacename>Message</interfacename> if a handler method returns a
      non-void value. Consider the interface and class:</para>

      <programlisting language="java">public interface ResponsiveTextMessageDelegate {

    <lineannotation><emphasis role="bold">// notice the return type...</emphasis></lineannotation>
731
    String receive(TextMessage message);
M
Mark Pollack 已提交
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
}</programlisting>

      <programlisting language="java">public class DefaultResponsiveTextMessageDelegate implements ResponsiveTextMessageDelegate {
    <lineannotation>// implementation elided for clarity...</lineannotation>
}</programlisting>

      <para>If the above
      <classname>DefaultResponsiveTextMessageDelegate</classname> is used in
      conjunction with a <classname>MessageListenerAdapter</classname> then
      any non-null value that is returned from the execution of the
      <literal>'receive(..)'</literal> method will (in the default
      configuration) be converted into a
      <interfacename>TextMessage</interfacename>. The resulting
      <interfacename>TextMessage</interfacename> will then be sent to the
      <interfacename>Destination</interfacename> (if one exists) defined in
      the JMS Reply-To property of the original
      <interfacename>Message</interfacename>, or the default
      <interfacename>Destination</interfacename> set on the
      <classname>MessageListenerAdapter</classname> (if one has been
      configured); if no <interfacename>Destination</interfacename> is found
      then an <classname>InvalidDestinationException</classname> will be
      thrown (and please note that this exception <emphasis>will
      not</emphasis> be swallowed and <emphasis>will</emphasis> propagate up
      the call stack).</para>
    </section>

    <section id="jms-tx-participation">
      <title>Processing messages within transactions</title>

      <para>Invoking a message listener within a transaction only requires
      reconfiguration of the listener container.</para>

      <para>Local resource transactions can simply be activated through the
      <literal>sessionTransacted</literal> flag on the listener container
      definition. Each message listener invocation will then operate within an
      active JMS transaction, with message reception rolled back in case of
      listener execution failure. Sending a response message (via
      <interfacename>SessionAwareMessageListener</interfacename>) will be part
      of the same local transaction, but any other resource operations (such
      as database access) will operate independently. This usually requires
      duplicate message detection in the listener implementation, covering the
      case where database processing has committed but message processing
      failed to commit.</para>

      <programlisting language="xml">&lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&gt;
    &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
    &lt;property name="destination" ref="destination"/&gt;
    &lt;property name="messageListener" ref="messageListener"/&gt;
    <emphasis role="bold">&lt;property name="sessionTransacted" value="true"/&gt;</emphasis>
&lt;/bean&gt;</programlisting>

      <para>For participating in an externally managed transaction, you will
      need to configure a transaction manager and use a listener container
      which supports externally managed transactions: typically
      <classname>DefaultMessageListenerContainer</classname>.</para>

      <para>To configure a message listener container for XA transaction
      participation, you'll want to configure a
      <classname>JtaTransactionManager</classname> (which, by default,
T
Thomas Risberg 已提交
791
      delegates to the Java EE server's transaction subsystem). Note that the
M
Mark Pollack 已提交
792
      underlying JMS ConnectionFactory needs to be XA-capable and properly
T
Thomas Risberg 已提交
793
      registered with your JTA transaction coordinator! (Check your Java EE
794
      server's configuration of JNDI resources.) This allows message reception
M
Mark Pollack 已提交
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
      as well as e.g. database access to be part of the same transaction (with
      unified commit semantics, at the expense of XA transaction log
      overhead).</para>

      <programlisting language="xml">&lt;bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager"/&gt;
</programlisting>

      <para>Then you just need to add it to our earlier container
      configuration. The container will take care of the rest.</para>

      <programlisting language="xml">&lt;bean id="jmsContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer"&gt;
    &lt;property name="connectionFactory" ref="connectionFactory"/&gt;
    &lt;property name="destination" ref="destination"/&gt;
    &lt;property name="messageListener" ref="messageListener"/&gt;
    <emphasis role="bold">&lt;property name="transactionManager" ref="transactionManager"/&gt;</emphasis>
&lt;/bean&gt;</programlisting>
    </section>
812 813 814 815 816
  </section>

  <section id="jms-jca-message-endpoint-manager">
    <title>Support for JCA Message Endpoints</title>

M
Mark Pollack 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852
    <para>Beginning with version 2.5, Spring also provides support for a
    JCA-based <interfacename>MessageListener</interfacename> container. The
    <classname>JmsMessageEndpointManager</classname> will attempt to
    automatically determine the <interfacename>ActivationSpec</interfacename>
    class name from the provider's
    <interfacename>ResourceAdapter</interfacename> class name. Therefore, it
    is typically possible to just provide Spring's generic
    <classname>JmsActivationSpecConfig</classname> as shown in the following
    example.</para>

    <programlisting language="xml">&lt;bean class="org.springframework.jms.listener.endpoint.JmsMessageEndpointManager"&gt;
    &lt;property name="resourceAdapter" ref="resourceAdapter"/&gt;
    &lt;property name="activationSpecConfig"&gt;
        &lt;bean class="org.springframework.jms.listener.endpoint.JmsActivationSpecConfig"&gt;
            &lt;property name="destinationName" value="myQueue"/&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
    &lt;property name="messageListener" ref="myMessageListener"/&gt;
&lt;/bean&gt;</programlisting>

    <para>Alternatively, you may set up a
    <classname>JmsMessageEndpointManager</classname> with a given
    <interfacename>ActivationSpec</interfacename> object. The
    <interfacename>ActivationSpec</interfacename> object may also come from a
    JNDI lookup (using <literal>&lt;jee:jndi-lookup&gt;</literal>).</para>

    <programlisting language="xml">&lt;bean class="org.springframework.jms.listener.endpoint.JmsMessageEndpointManager"&gt;
    &lt;property name="resourceAdapter" ref="resourceAdapter"/&gt;
    &lt;property name="activationSpec"&gt;
        &lt;bean class="org.apache.activemq.ra.ActiveMQActivationSpec"&gt;
            &lt;property name="destination" value="myQueue"/&gt;
            &lt;property name="destinationType" value="javax.jms.Queue"/&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
    &lt;property name="messageListener" ref="myMessageListener"/&gt;
&lt;/bean&gt;</programlisting>
853 854 855 856 857

    <para>Using Spring's <classname>ResourceAdapterFactoryBean</classname>,
    the target <interfacename>ResourceAdapter</interfacename> may be
    configured locally as depicted in the following example.</para>

M
Mark Pollack 已提交
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
    <programlisting language="xml">&lt;bean id="resourceAdapter" class="org.springframework.jca.support.ResourceAdapterFactoryBean"&gt;
    &lt;property name="resourceAdapter"&gt;
        &lt;bean class="org.apache.activemq.ra.ActiveMQResourceAdapter"&gt;
            &lt;property name="serverUrl" value="tcp://localhost:61616"/&gt;
        &lt;/bean&gt;
    &lt;/property&gt;
    &lt;property name="workManager"&gt;
        &lt;bean class="org.springframework.jca.work.SimpleTaskWorkManager"/&gt;
    &lt;/property&gt;
&lt;/bean&gt;</programlisting>

    <para>The specified <interfacename>WorkManager</interfacename> may also
    point to an environment-specific thread pool - typically through
    <classname>SimpleTaskWorkManager's</classname> "asyncTaskExecutor"
    property. Consider defining a shared thread pool for all your
    <interfacename>ResourceAdapter</interfacename> instances if you happen to
    use multiple adapters.</para>
875 876

    <para>In some environments (e.g. WebLogic 9 or above), the entire
M
Mark Pollack 已提交
877 878 879
    <interfacename>ResourceAdapter</interfacename> object may be obtained from
    JNDI instead (using <literal>&lt;jee:jndi-lookup&gt;</literal>). The
    Spring-based message listeners can then interact with the server-hosted
880 881 882
    <interfacename>ResourceAdapter</interfacename>, also using the server's
    built-in <interfacename>WorkManager</interfacename>.</para>

M
Mark Pollack 已提交
883 884
    <para>Please consult the JavaDoc for
    <classname>JmsMessageEndpointManager</classname>,
885 886 887
    <classname>JmsActivationSpecConfig</classname>, and
    <classname>ResourceAdapterFactoryBean</classname> for more details.</para>

M
Mark Pollack 已提交
888 889
    <para>Spring also provides a generic JCA message endpoint manager which is
    not tied to JMS:
890
    <classname>org.springframework.jca.endpoint.GenericMessageEndpointManager</classname>.
M
Mark Pollack 已提交
891
    This component allows for using any message listener type (e.g. a CCI
892
    MessageListener) and any provider-specific ActivationSpec object. Check
M
Mark Pollack 已提交
893 894 895 896
    out your JCA provider's documentation to find out about the actual
    capabilities of your connector, and consult
    <classname>GenericMessageEndpointManager</classname>'s JavaDoc for the
    Spring-specific configuration details.</para>
897 898 899

    <note>
      <para>JCA-based message endpoint management is very analogous to EJB 2.1
M
Mark Pollack 已提交
900 901 902 903 904 905
      Message-Driven Beans; it uses the same underlying resource provider
      contract. Like with EJB 2.1 MDBs, any message listener interface
      supported by your JCA provider can be used in the Spring context as
      well. Spring nevertheless provides explicit 'convenience' support for
      JMS, simply because JMS is the most common endpoint API used with the
      JCA endpoint management contract.</para>
906 907 908 909 910 911
    </note>
  </section>

  <section id="jms-namespace">
    <title>JMS Namespace Support</title>

M
Mark Pollack 已提交
912 913 914 915 916 917
    <para>Spring 2.5 introduces an XML namespace for simplifying JMS
    configuration. To use the JMS namespace elements you will need to
    reference the JMS schema:</para>

    <programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
918
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
M
Mark Pollack 已提交
919
       <emphasis role="bold">xmlns:jms="http://www.springframework.org/schema/jms"</emphasis>
920
       xsi:schemaLocation="
921 922
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
<emphasis role="bold">http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd"</emphasis>&gt;
M
Mark Pollack 已提交
923 924

<lineannotation>&lt;!-- <literal>&lt;bean/&gt;</literal> definitions here --&gt;</lineannotation>
925

M
Mark Pollack 已提交
926
&lt;/beans&gt;</programlisting>
927

M
Mark Pollack 已提交
928 929 930 931 932
    <para>The namespace consists of two top-level elements:
    <literal>&lt;listener-container/&gt;</literal> and
    <literal>&lt;jca-listener-container/&gt;</literal> both of which may
    contain one or more <literal>&lt;listener/&gt;</literal> child elements.
    Here is an example of a basic configuration for two listeners.</para>
933

M
Mark Pollack 已提交
934
    <programlisting language="xml">&lt;jms:listener-container&gt;
935

M
Mark Pollack 已提交
936
    &lt;jms:listener destination="queue.orders" ref="orderService" method="placeOrder"/&gt;
937

M
Mark Pollack 已提交
938
    &lt;jms:listener destination="queue.confirmations" ref="confirmationLogger" method="log"/&gt;
939

M
Mark Pollack 已提交
940
&lt;/jms:listener-container&gt;</programlisting>
941

M
Mark Pollack 已提交
942 943 944
    <para>The example above is equivalent to creating two distinct listener
    container bean definitions and two distinct
    <classname>MessageListenerAdapter</classname> bean definitions as
945 946 947
    demonstrated in <xref linkend="jms-receiving-async-message-listener-adapter" />.
    In addition to the attributes shown above, the <literal>listener</literal> element
    may contain several optional ones. The following table describes all available
M
Mark Pollack 已提交
948
    attributes:</para>
949 950

    <table id="jms-namespace-listener-tbl">
M
Mark Pollack 已提交
951 952 953
      <title>Attributes of the JMS <literal>&lt;listener&gt;</literal>
      element</title>

954
      <tgroup cols="2">
M
Mark Pollack 已提交
955 956 957 958
        <colspec colname="c1" colwidth="2*" />

        <colspec colname="c2" colwidth="4*" />

959 960 961
        <thead>
          <row>
            <entry>Attribute</entry>
M
Mark Pollack 已提交
962

963 964 965
            <entry>Description</entry>
          </row>
        </thead>
M
Mark Pollack 已提交
966

967 968 969
        <tbody>
          <row>
            <entry>id</entry>
M
Mark Pollack 已提交
970 971 972 973

            <entry><para>A bean name for the hosting listener container. If
            not specified, a bean name will be automatically
            generated.</para></entry>
974
          </row>
M
Mark Pollack 已提交
975

976
          <row>
M
Mark Pollack 已提交
977 978 979 980 981 982
            <entry>destination <emphasis
            role="bold">(required)</emphasis></entry>

            <entry><para>The destination name for this listener, resolved
            through the <interfacename>DestinationResolver</interfacename>
            strategy.</para></entry>
983
          </row>
M
Mark Pollack 已提交
984

985 986
          <row>
            <entry>ref <emphasis role="bold">(required)</emphasis></entry>
M
Mark Pollack 已提交
987 988

            <entry><para>The bean name of the handler object.</para></entry>
989
          </row>
M
Mark Pollack 已提交
990

991 992
          <row>
            <entry>method</entry>
M
Mark Pollack 已提交
993 994 995 996 997 998

            <entry><para>The name of the handler method to invoke. If the
            <literal>ref</literal> points to a
            <interfacename>MessageListener</interfacename> or Spring
            <interfacename>SessionAwareMessageListener</interfacename>, this
            attribute may be omitted.</para></entry>
999
          </row>
M
Mark Pollack 已提交
1000

1001 1002
          <row>
            <entry>response-destination</entry>
M
Mark Pollack 已提交
1003 1004 1005 1006 1007 1008 1009 1010

            <entry><para>The name of the default response destination to send
            response messages to. This will be applied in case of a request
            message that does not carry a "JMSReplyTo" field. The type of this
            destination will be determined by the listener-container's
            "destination-type" attribute. Note: This only applies to a
            listener method with a return value, for which each result object
            will be converted into a response message.</para></entry>
1011
          </row>
M
Mark Pollack 已提交
1012

1013 1014
          <row>
            <entry>subscription</entry>
M
Mark Pollack 已提交
1015 1016 1017

            <entry><para>The name of the durable subscription, if
            any.</para></entry>
1018
          </row>
M
Mark Pollack 已提交
1019

1020 1021
          <row>
            <entry>selector</entry>
M
Mark Pollack 已提交
1022 1023 1024

            <entry><para>An optional message selector for this
            listener.</para></entry>
1025 1026 1027 1028 1029
          </row>
        </tbody>
      </tgroup>
    </table>

M
Mark Pollack 已提交
1030 1031 1032 1033 1034 1035 1036
    <para>The <literal>&lt;listener-container/&gt;</literal> element also
    accepts several optional attributes. This allows for customization of the
    various strategies (for example, <property>taskExecutor</property> and
    <property>destinationResolver</property>) as well as basic JMS settings
    and resource references. Using these attributes, it is possible to define
    highly-customized listener containers while still benefiting from the
    convenience of the namespace.</para>
1037

M
Mark Pollack 已提交
1038
    <programlisting language="xml">&lt;jms:listener-container connection-factory="myConnectionFactory"
1039 1040 1041
                        task-executor="myTaskExecutor"
                        destination-resolver="myDestinationResolver"
                        transaction-manager="myTransactionManager"
M
Mark Pollack 已提交
1042 1043 1044
                        concurrency="10"&gt;

    &lt;jms:listener destination="queue.orders" ref="orderService" method="placeOrder"/&gt;
1045

M
Mark Pollack 已提交
1046
    &lt;jms:listener destination="queue.confirmations" ref="confirmationLogger" method="log"/&gt;
1047

M
Mark Pollack 已提交
1048
&lt;/jms:listener-container&gt;</programlisting>
1049

M
Mark Pollack 已提交
1050 1051 1052
    <para>The following table describes all available attributes. Consult the
    class-level Javadoc of the
    <classname>AbstractMessageListenerContainer</classname> and its concrete
1053
    subclasses for more details on the individual properties. The Javadoc also
M
Mark Pollack 已提交
1054 1055
    provides a discussion of transaction choices and message redelivery
    scenarios.</para>
1056 1057

    <table id="jms-namespace-listener-container-tbl">
M
Mark Pollack 已提交
1058 1059 1060
      <title>Attributes of the JMS
      <literal>&lt;listener-container&gt;</literal> element</title>

1061
      <tgroup cols="2">
M
Mark Pollack 已提交
1062 1063 1064 1065
        <colspec colname="c1" colwidth="2*" />

        <colspec colname="c2" colwidth="4*" />

1066 1067 1068
        <thead>
          <row>
            <entry>Attribute</entry>
M
Mark Pollack 已提交
1069

1070 1071 1072
            <entry>Description</entry>
          </row>
        </thead>
M
Mark Pollack 已提交
1073

1074 1075 1076
        <tbody>
          <row>
            <entry>container-type</entry>
M
Mark Pollack 已提交
1077 1078 1079 1080 1081 1082

            <entry><para>The type of this listener container. Available
            options are: <literal>default</literal>,
            <literal>simple</literal>, <literal>default102</literal>, or
            <literal>simple102</literal> (the default value is
            <literal>'default'</literal>).</para></entry>
1083
          </row>
M
Mark Pollack 已提交
1084

1085 1086
          <row>
            <entry>connection-factory</entry>
M
Mark Pollack 已提交
1087 1088 1089 1090 1091

            <entry><para>A reference to the JMS
            <interfacename>ConnectionFactory</interfacename> bean (the default
            bean name is
            <literal>'connectionFactory'</literal>).</para></entry>
1092
          </row>
M
Mark Pollack 已提交
1093

1094 1095
          <row>
            <entry>task-executor</entry>
M
Mark Pollack 已提交
1096 1097 1098 1099

            <entry><para>A reference to the Spring
            <interfacename>TaskExecutor</interfacename> for the JMS listener
            invokers.</para></entry>
1100
          </row>
M
Mark Pollack 已提交
1101

1102 1103
          <row>
            <entry>destination-resolver</entry>
M
Mark Pollack 已提交
1104 1105 1106 1107 1108

            <entry><para>A reference to the
            <interfacename>DestinationResolver</interfacename> strategy for
            resolving JMS
            <interfacename>Destinations</interfacename>.</para></entry>
1109
          </row>
M
Mark Pollack 已提交
1110

1111 1112
          <row>
            <entry>message-converter</entry>
M
Mark Pollack 已提交
1113 1114 1115 1116 1117

            <entry><para>A reference to the
            <interfacename>MessageConverter</interfacename> strategy for
            converting JMS Messages to listener method arguments. Default is a
            <classname>SimpleMessageConverter</classname>.</para></entry>
1118
          </row>
M
Mark Pollack 已提交
1119

1120 1121
          <row>
            <entry>destination-type</entry>
M
Mark Pollack 已提交
1122 1123 1124 1125 1126

            <entry><para>The JMS destination type for this listener:
            <literal>queue</literal>, <literal>topic</literal> or
            <literal>durableTopic</literal>. The default is
            <literal>queue</literal>.</para></entry>
1127
          </row>
M
Mark Pollack 已提交
1128

1129 1130
          <row>
            <entry>client-id</entry>
M
Mark Pollack 已提交
1131 1132 1133

            <entry><para>The JMS client id for this listener container. Needs
            to be specified when using durable subscriptions.</para></entry>
1134
          </row>
M
Mark Pollack 已提交
1135

1136 1137
          <row>
            <entry>cache</entry>
M
Mark Pollack 已提交
1138 1139 1140 1141 1142 1143 1144 1145

            <entry><para>The cache level for JMS resources:
            <literal>none</literal>, <literal>connection</literal>,
            <literal>session</literal>, <literal>consumer</literal> or
            <literal>auto</literal>. By default (<literal>auto</literal>), the
            cache level will effectively be "consumer", unless an external
            transaction manager has been specified - in which case the
            effective default will be <literal>none</literal> (assuming
T
Thomas Risberg 已提交
1146
            Java EE-style transaction management where the given
M
Mark Pollack 已提交
1147
            ConnectionFactory is an XA-aware pool).</para></entry>
1148
          </row>
M
Mark Pollack 已提交
1149

1150 1151
          <row>
            <entry>acknowledge</entry>
M
Mark Pollack 已提交
1152 1153 1154 1155 1156 1157 1158 1159 1160

            <entry><para>The native JMS acknowledge mode:
            <literal>auto</literal>, <literal>client</literal>,
            <literal>dups-ok</literal> or <literal>transacted</literal>. A
            value of <literal>transacted</literal> activates a locally
            transacted <interfacename>Session</interfacename>. As an
            alternative, specify the <literal>transaction-manager</literal>
            attribute described below. Default is
            <literal>auto</literal>.</para></entry>
1161
          </row>
M
Mark Pollack 已提交
1162

1163 1164
          <row>
            <entry>transaction-manager</entry>
M
Mark Pollack 已提交
1165 1166 1167 1168 1169 1170 1171

            <entry><para>A reference to an external
            <interfacename>PlatformTransactionManager</interfacename>
            (typically an XA-based transaction coordinator, e.g. Spring's
            <classname>JtaTransactionManager</classname>). If not specified,
            native acknowledging will be used (see "acknowledge"
            attribute).</para></entry>
1172
          </row>
M
Mark Pollack 已提交
1173

1174 1175
          <row>
            <entry>concurrency</entry>
M
Mark Pollack 已提交
1176 1177 1178 1179 1180 1181 1182 1183 1184

            <entry><para>The number of concurrent sessions/consumers to start
            for each listener. Can either be a simple number indicating the
            maximum number (e.g. "5") or a range indicating the lower as well
            as the upper limit (e.g. "3-5"). Note that a specified minimum is
            just a hint and might be ignored at runtime. Default is 1; keep
            concurrency limited to 1 in case of a topic listener or if queue
            ordering is important; consider raising it for general
            queues.</para></entry>
1185
          </row>
M
Mark Pollack 已提交
1186

1187 1188
          <row>
            <entry>prefetch</entry>
M
Mark Pollack 已提交
1189 1190 1191 1192

            <entry><para>The maximum number of messages to load into a single
            session. Note that raising this number might lead to starvation of
            concurrent consumers!</para></entry>
1193 1194 1195
          </row>
        </tbody>
      </tgroup>
M
Mark Pollack 已提交
1196
    </table>
1197

M
Mark Pollack 已提交
1198 1199 1200 1201
    <para>Configuring a JCA-based listener container with the "jms" schema
    support is very similar.</para>

    <programlisting language="xml">&lt;jms:jca-listener-container resource-adapter="myResourceAdapter"
1202 1203
                            destination-resolver="myDestinationResolver"
                            transaction-manager="myTransactionManager"
M
Mark Pollack 已提交
1204
                            concurrency="10"&gt;
1205

M
Mark Pollack 已提交
1206
    &lt;jms:listener destination="queue.orders" ref="myMessageListener"/&gt;
1207

M
Mark Pollack 已提交
1208
&lt;/jms:jca-listener-container&gt;</programlisting>
1209

M
Mark Pollack 已提交
1210 1211
    <para>The available configuration options for the JCA variant are
    described in the following table:</para>
1212 1213

    <table id="jms-namespace-jca-listener-container-tbl">
M
Mark Pollack 已提交
1214 1215 1216
      <title>Attributes of the JMS
      <literal>&lt;jca-listener-container/&gt;</literal> element</title>

1217
      <tgroup cols="2">
M
Mark Pollack 已提交
1218 1219 1220 1221
        <colspec colname="c1" colwidth="2*" />

        <colspec colname="c2" colwidth="4*" />

1222 1223 1224
        <thead>
          <row>
            <entry>Attribute</entry>
M
Mark Pollack 已提交
1225

1226 1227 1228
            <entry>Description</entry>
          </row>
        </thead>
M
Mark Pollack 已提交
1229

1230 1231 1232
        <tbody>
          <row>
            <entry>resource-adapter</entry>
M
Mark Pollack 已提交
1233 1234 1235 1236

            <entry><para>A reference to the JCA
            <interfacename>ResourceAdapter</interfacename> bean (the default
            bean name is <literal>'resourceAdapter'</literal>).</para></entry>
1237
          </row>
M
Mark Pollack 已提交
1238

1239 1240
          <row>
            <entry>activation-spec-factory</entry>
M
Mark Pollack 已提交
1241 1242 1243 1244 1245 1246

            <entry><para>A reference to the
            <interfacename>JmsActivationSpecFactory</interfacename>. The
            default is to autodetect the JMS provider and its
            <interfacename>ActivationSpec</interfacename> class (see
            <classname>DefaultJmsActivationSpecFactory</classname>)</para></entry>
1247
          </row>
M
Mark Pollack 已提交
1248

1249 1250
          <row>
            <entry>destination-resolver</entry>
M
Mark Pollack 已提交
1251 1252 1253 1254 1255

            <entry><para>A reference to the
            <interfacename>DestinationResolver</interfacename> strategy for
            resolving JMS <interfacename>Destinations</interfacename>.
            </para></entry>
1256
          </row>
M
Mark Pollack 已提交
1257

1258 1259
          <row>
            <entry>message-converter</entry>
M
Mark Pollack 已提交
1260 1261 1262 1263 1264

            <entry><para>A reference to the
            <interfacename>MessageConverter</interfacename> strategy for
            converting JMS Messages to listener method arguments. Default is a
            <classname>SimpleMessageConverter</classname>.</para></entry>
1265
          </row>
M
Mark Pollack 已提交
1266

1267 1268
          <row>
            <entry>destination-type</entry>
M
Mark Pollack 已提交
1269 1270 1271 1272 1273

            <entry><para>The JMS destination type for this listener:
            <literal>queue</literal>, <literal>topic</literal> or
            <literal>durableTopic</literal>. The default is
            <literal>queue</literal>.</para></entry>
1274
          </row>
M
Mark Pollack 已提交
1275

1276 1277
          <row>
            <entry>client-id</entry>
M
Mark Pollack 已提交
1278 1279 1280

            <entry><para>The JMS client id for this listener container. Needs
            to be specified when using durable subscriptions.</para></entry>
1281
          </row>
M
Mark Pollack 已提交
1282

1283 1284
          <row>
            <entry>acknowledge</entry>
M
Mark Pollack 已提交
1285 1286 1287 1288 1289 1290 1291 1292 1293

            <entry><para>The native JMS acknowledge mode:
            <literal>auto</literal>, <literal>client</literal>,
            <literal>dups-ok</literal> or <literal>transacted</literal>. A
            value of <literal>transacted</literal> activates a locally
            transacted <interfacename>Session</interfacename>. As an
            alternative, specify the <literal>transaction-manager</literal>
            attribute described below. Default is
            <literal>auto</literal>.</para></entry>
1294
          </row>
M
Mark Pollack 已提交
1295

1296 1297
          <row>
            <entry>transaction-manager</entry>
M
Mark Pollack 已提交
1298 1299 1300 1301 1302 1303 1304

            <entry><para>A reference to a Spring
            <classname>JtaTransactionManager</classname> or a
            <interfacename>javax.transaction.TransactionManager</interfacename>
            for kicking off an XA transaction for each incoming message. If
            not specified, native acknowledging will be used (see the
            "acknowledge" attribute).</para></entry>
1305
          </row>
M
Mark Pollack 已提交
1306

1307 1308
          <row>
            <entry>concurrency</entry>
M
Mark Pollack 已提交
1309 1310 1311 1312 1313 1314 1315

            <entry><para>The number of concurrent sessions/consumers to start
            for each listener. Can either be a simple number indicating the
            maximum number (e.g. "5") or a range indicating the lower as well
            as the upper limit (e.g. "3-5"). Note that a specified minimum is
            just a hint and will typically be ignored at runtime when using a
            JCA listener container. Default is 1.</para></entry>
1316
          </row>
M
Mark Pollack 已提交
1317

1318 1319
          <row>
            <entry>prefetch</entry>
M
Mark Pollack 已提交
1320 1321 1322 1323

            <entry><para>The maximum number of messages to load into a single
            session. Note that raising this number might lead to starvation of
            concurrent consumers!</para></entry>
1324 1325 1326 1327 1328
          </row>
        </tbody>
      </tgroup>
    </table>
  </section>
M
Mark Pollack 已提交
1329
</chapter>