Red Hat Training

A Red Hat training course is available for Red Hat JBoss Enterprise Application Platform

Chapter 4. Message-Driven Beans

4.1. Message-Driven Beans

Message-driven Beans (MDBs) provide an event driven model for application development. The methods of MDBs are not injected into or invoked from client code but are triggered by the receipt of messages from a messaging service such as a Java Messaging Service (JMS) server. The Java EE specification requires that JMS is supported but other messaging systems can be supported as well.

With an MDB, Java EE applications process messages asynchronously. An MDB functions as a JMS or JCA message listener. The messages can be sent by a Java EE component, for example an application client, or another enterprise bean, or by a non-Java EE application.

4.2. Message-Driven Beans Controlled Delivery

JBoss EAP provides three attributes that control active reception of messages on a specific MDB:

4.2.1. Delivery Active

The delivery active configuration of the message-driven beans (MDB) indicates whether the MDB is receiving messages or not. If an MDB is not receiving messages, then the messages will be saved in the queue or topic according to the topic or queue rules.

You can configure the active attribute of the delivery-group using XML or annotations, and you can change its value after deployment using the management CLI. By default, the active attribute is activated and delivery of messages occurs as soon as the MDB is deployed.

Configuring Delivery Active in the jboss-ejb3.xml File

In the jboss-ejb3.xml file, configure the value of active as false to indicate that the MDB will not be receiving messages as soon as it is deployed:

<?xml version="1.1" encoding="UTF-8"?>
<jboss:ejb-jar xmlns:jboss=""

If you want to apply the active value to all MDBs in your application, you can use a wildcard * in place of the ejb-name.

Configuring Delivery Active Using Annotations

You can also use the org.jboss.ejb3.annotation.DeliveryActive annotation. For example:

@MessageDriven(name = "HelloWorldMDB", activationConfig = {
 @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
 @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/HELLOWORLDMDBQueue"),
 @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })

public class HelloWorldMDB implements MessageListener {
    public void onMessage(Message rcvMessage) {
      // ...

If you use Maven to build your project, make sure you add the following dependency to the pom.xml file of your project:

Configuring Delivery Active Using the Management CLI

You can configure the active attribute of the delivery-group after deployment using the management CLI. These management operations dynamically change the value of the active attribute, enabling or disabling delivery for the MDB. This method of changing the delivery active value does not persist if you restart the server. At runtime, connect to the instance you want to manage, then enter the path of the MDB for which you want to manage the delivery. For example:

  • Connect to the instance you want to manage:

    cd deployment=jboss-helloworld-mdb.war/subsystem=ejb3/message-driven-bean=HelloWorldQueueMDB
  • To stop the delivery to the MDB:

  • To start the delivery to the MDB:

View the MDB Delivery Active Status

You can view the current delivery active status of any MDB using the management console:

  1. Choose Deployments and select the deployed MDB application. Click on View.
  2. Expand the application and select the subsystem message-driven-bean.
  3. Select the child resource, for example HelloWorldQueueMDB. Click on View.


You see the status as Delivery active: true or Delivery active: false.

4.2.2. Delivery Groups

Delivery groups provide a way to manage the delivery-active state for a group of MDBs. Every MDB belonging to a delivery group has delivery active if and only if that group is active, and has delivery inactive whenever the group is not active.

You can add a delivery group to the ejb3 subsystem using either the XML configuration or the management CLI.

Configuring Delivery Group in the jboss-ejb3.xml File


On the server side, delivery-groups can be enabled by having their active attribute set to true, or disabled by having their active attribute set to false, as shown in the example below:

<delivery-group name="group" active="true"/>

Configuring Delivery Group Using the Management CLI

The state of delivery-groups can be updated using the management CLI. For example:


When you set the delivery active in the jboss-ejb3.xml file or using the annotation, it persists on server restart. However, when you use the management CLI to stop or start the delivery, it does not persist on server restart.

4.2.3. Clustered Singleton MDBs


This feature is provided as Technology Preview only. It is not supported for use in a production environment, and it may be subject to significant future changes. See Technology Preview Features Support Scope on the Red Hat Customer Portal for information about the support scope for Technology Preview features.

When an MDB is identified as a clustered singleton and is deployed in a cluster, only one node is active. This node can consume messages serially. When the server node fails, the active node from the clustered singleton MDBs starts consuming the messages.

Identify an MDB as a Clustered Singleton

You can use one of the following procedures to identify an MDB as a clustered singleton.

  • Use the clustered-singleton XML element as shown in the example below:

    <jboss:ejb-jar xmlns:jboss=""
  • In your MDB class, use the @org.jboss.ejb3.annotation.ClusteredSingleton. This procedure requires no extra configuration at the server. You need to run the service in a clustered environment.

You have to activate the delivery-group in the entire cluster, specifically, in all nodes of the cluster, because you do not know which node of the cluster is chosen to be the singleton master. If the server chooses a node to be singleton master, and that node does not have the required delivery-group activated, no node in the cluster receives the messages.

4.3. Create a JMS-based Message-Driven Bean in Red Hat JBoss Developer Studio

This procedure shows how to add a JMS-based Message-Driven Bean to a project in Red Hat JBoss Developer Studio. This procedure creates an EJB 3.x Message-Driven Bean that uses annotations.


  • You must have an existing project open in Red Hat JBoss Developer Studio.
  • You must know the name and type of the JMS destination that the bean will be listening to.
  • Support for Java Messaging Service (JMS) must be enabled in the JBoss EAP configuration to which this bean will be deployed.

Add a JMS-based Message-Driven Bean in Red Hat JBoss Developer Studio

  1. Open the Create EJB 3.x Message-Driven Bean Wizard: Go to File → New → Other. Select EJB/Message-Driven Bean (EJB 3.x) and click the Next button.

    Figure 4.1. Create EJB 3.x Message-Driven Bean Wizard

    Create EJB 3.x Message-Driven Bean Wizard
  2. Specify class file destination details: There are three sets of details to specify for the bean class here: Project, Java class, and message destination.

    • Project:

      • If multiple projects exist in the Workspace, ensure that the correct one is selected in the Project menu.
      • The folder where the source file for the new bean will be created is ejbModule under the selected project’s directory. Only change this if you have a specific requirement.
    • Java Class:

      • The required fields are: Java package and class name.
      • It is not necessary to supply a Superclass unless the business logic of your application requires it.
    • Message Destination:

      • These are the details you must supply for a JMS-based Message-Driven Bean:

        • Destination name, which is the queue or topic name that contains the messages that the bean will respond to.
        • By default the JMS checkbox is selected. Do not change this.
        • Set Destination type to Queue or Topic as required.

          Click the Next button.

  3. Enter Message-Driven Bean specific information: The default values here are suitable for a JMS-based Message-Driven bean using Container-managed transactions.

    • Change the Transaction type to Bean if the Bean will use Bean-managed transactions.
    • Change the Bean name if a different bean name than the class name is required.
    • The JMS Message Listener interface will already be listed. You do not need to add or remove any interfaces unless they are specific to your application’s business logic.
    • Leave the checkboxes for creating method stubs selected.

      Click the Finish button.


The Message-Driven Bean is created with stub methods for the default constructor and the onMessage() method. A Red Hat JBoss Developer Studio editor window opens with the corresponding file.

4.4. Specifying a Resource Adapter in jboss-ejb3.xml for an MDB

In the jboss-ejb3.xml deployment descriptor you can specify a resource adapter for an MDB to use.

To specify a resource adapter in jboss-ejb3.xml for an MDB, use the following example.

Example: jboss-ejb3.xml Configuration for an MDB Resource Adapter

<jboss xmlns=""

For a resource adapter located in an EAR, you must use the following syntax for <mdb:resource-adapter-name>:

  • For a resource adapter that is in another EAR:

  • For a resource adapter that is in the same EAR as the MDB, you can omit the EAR name:


4.5. Enable EJB and MDB Property Substitution in an Application

Red Hat JBoss Enterprise Application Platform allows you to enable property substitution in EJBs and MDBs using the @ActivationConfigProperty and @Resource annotations. Property substitution requires the following configuration and code changes.

The following examples demonstrate how to modify the helloworld-mdb quickstart that ships with JBoss EAP to use property substitution. See the helloworld-mdb-propertysubstitution quickstart for the completed working example.

4.5.1. Configure the Server to Enable Property Substitution

To enable property substitution in the JBoss EAP server, you must set the <annotation-property-replacement> attribute in the ee subsystem of the server configuration file to true.

  1. Back up the server configuration file.

    The helloworld-mdb-property-substitution quickstart example requires the full profile for a standalone server, so this is the standalone/configuration/standalone-full.xml file. If you are running your server in a managed domain, this is the domain/configuration/domain.xml file.

  2. Navigate to the JBoss EAP install directory and start the server with the full profile.

    $ EAP_HOME/bin/ -c standalone-full.xml

    For Windows Server, use the EAP_HOME\bin\standalone.bat script.

  3. Launch the management CLI.

    $ EAP_HOME/bin/ --connect

    For Windows Server, use the EAP_HOME\bin\jboss-cli.bat script.

  4. Type the following command to enable annotation property substitution.


    You should see the following result.

    {"outcome" => "success"}
  5. Review the changes to the JBoss EAP server configuration file. The ee subsystem should now contain the following XML.

    Example ee Subsystem Configuration

    <subsystem xmlns="urn:jboss:domain:ee:4.0">

4.5.2. Define the System Properties

You can specify the system properties in the server configuration file or you can pass them as command line arguments when you start the JBoss EAP server. System properties defined in the server configuration file take precedence over those passed on the command line when you start the server. Define the System Properties in the Server Configuration File

  1. Launch the management CLI as described above.
  2. Use the following command syntax to configure a system property in the JBoss EAP server.

    Syntax to Add a System Property


    The following system properties are configured for the helloworld-mdb-propertysubstitution quickstart.

    Example Commands to Add System Properties


  3. Review the changes to the JBoss EAP server configuration file. The following system properties should now appear in the after the <extensions>.

    Example System Properties Configuration

        <property name="property.helloworldmdb.queue" value="java:/queue/HELLOWORLDMDBPropQueue"/>
        <property name="property.helloworldmdb.topic" value="java:/topic/HELLOWORLDMDBPropTopic"/>
        <property name="property.connection.factory" value="java:/ConnectionFactory"/>
    </system-properties> Pass the System Properties as Arguments on Server Start

If you prefer, you can instead pass the arguments on the command line when you start the JBoss EAP server in the form of -DPROPERTY_NAME=PROPERTY_VALUE. The following is an example of how to pass the arguments for the system properties defined in the previous section.

Example Server Start Command Passing System Properties

EAP_HOME/bin/ -c standalone-full.xml  -Dproperty.helloworldmdb.queue=java:/queue/HELLOWORLDMDBPropQueue  -Dproperty.helloworldmdb.topic=java:/topic/HELLOWORLDMDBPropTopic  -Dproperty.connection.factory=java:/ConnectionFactory

4.5.3. Modify the Application Code to Use the System Property Substitutions

Replace the hard-coded @ActivationConfigProperty and @Resource annotation values with substitutions for the newly defined system properties. The following are examples of how to change the helloworld-mdb quickstart to use the newly defined system property substitutions.

  1. Change the @ActivationConfigProperty destination property value in the HelloWorldQueueMDB class to use the substitution for the system property. The @MessageDriven annotation should now look like this:

    HelloWorldQueueMDB Code Example

    @MessageDriven(name = "HelloWorldQueueMDB", activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "${property.helloworldmdb.queue}"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })

  2. Change the @ActivationConfigProperty destination property value in the HelloWorldTopicMDB class to use the substitution for the system property. The @MessageDriven annotation should now look like this:

    HelloWorldTopicMDB Code Example

    @MessageDriven(name = "HelloWorldQTopicMDB", activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "${property.helloworldmdb.topic}"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })

  3. Change the @Resource annotations in the HelloWorldMDBServletClient class to use the system property substitutions. The code should now look like this:

    HelloWorldMDBServletClient Code Example

     * Definition of the two JMS destinations used by the quickstart
     * (one queue and one topic).
         value = {
                 name = "java:/${property.helloworldmdb.queue}",
                 interfaceName = "javax.jms.Queue",
                 destinationName = "HelloWorldMDBQueue"
                 name = "java:/${property.helloworldmdb.topic}",
                 interfaceName = "javax.jms.Topic",
                 destinationName = "HelloWorldMDBTopic"
     * <p>
     * A simple servlet 3 as client that sends several messages to a queue or a topic.
     * </p>
     * <p>
     * The servlet is registered and mapped to /HelloWorldMDBServletClient using the {@linkplain WebServlet
     * @HttpServlet}.
     * </p>
     * @author Serge Pagop (
    public class HelloWorldMDBServletClient extends HttpServlet {
        private static final long serialVersionUID = -8314035702649252239L;
        private static final int MSG_COUNT = 5;
        private JMSContext context;
        @Resource(lookup = "${property.helloworldmdb.queue}")
        private Queue queue;
        @Resource(lookup = "${property.helloworldmdb.topic}")
        private Topic topic;
      <!-- Remainder of code can be found in the `helloworld-mdb-propertysubstitution` quickstart. -->

  4. Modify the activemq-jms.xml file to use the system property substitution values.

    Example .activemq-jms.xml File

    <?xml version="1.0" encoding="UTF-8"?>
    <messaging-deployment xmlns="urn:jboss:messaging-activemq-deployment:1.0">
                <jms-queue name="HELLOWORLDMDBQueue">
                    <entry name="${property.helloworldmdb.queue}"/>
                <jms-topic name="HELLOWORLDMDBTopic">
                    <entry name="${property.helloworldmdb.topic}"/>

  5. Deploy the application. The application now uses the values specified by the system properties for the @Resource and @ActivationConfigProperty property values.

4.6. Activation Configuration Properties

4.6.1. Configuring MDBs Using Annotations

You can configure activation properties by using the @MessageDriven element and sub-elements which correspond to the @ActivationConfigProperty annotation. @ActivationConfigProperty is an array of activation configuration properties for MDBs. The @ActivationConfigProperty annotation specification is as follows:

public @interface ActivationConfigProperty
	String propertyName();
	String propertyValue();

Example showing @ActivationConfigProperty

activationConfig =
    @ActivationConfigProperty(propertyName = "destinationType",propertyValue = "javax.jms.Queue"),
    @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"),

4.6.2. Configuring MDBs Using Deployment Descriptor

The <message-driven> element in the ejb-jar.xml defines the bean as an MDB. The <activation-config> and elements contain the MDB configuration via the activation-config-property elements.

Example ejb-jar.xml

<?xml version="1.1" encoding="UTF-8"?>
<jboss:ejb-jar xmlns:jboss=""

Table 4.1. Activation Configuration Properties defined by JMS Specifications



The JNDI name of the queue or topic. This is a mandatory value.


The lookup name of an administratively defined javax.jms.ConnectionFactory, javax.jms.QueueConnectionFactory or javax.jms.TopicConnectionFactory object that will be used to connect to the JMS provider from which the endpoint would receive messages.

If not defined explicitly, pooled connection factory with name activemq-ra is used.


The type of destination valid values are javax.jms.Queue or javax.jms.Topic. This is a mandatory value.


The value for a messageSelector property is a string which is used to select a subset of the available messages. Its syntax is based on a subset of the SQL 92 conditional expression syntax and is described in detail in JMS specification. Specifying a value for the messageSelector property on the ActivationSpec JavaBean is optional.


The type of acknowledgement when not using transacted JMS. Valid values are Auto-acknowledge or Dups-ok-acknowledge. This is not a mandatory value.

The default value is Auto-acknowledge.


The client ID of the connection. This is not a mandatory value.


Whether topic subscriptions are durable. Valid values are Durable or NonDurable. This is not a mandatory value.

The default value is NonDurable.


The subscription name of the topic subscription. This is not a mandatory value.

Table 4.2. Activation Configuration Properties defined by JBoss EAP



Using this property with useJNDI=true has the same meaning as destinationLookup. Using it with useJNDI=false, the destination is not looked up, but it is instantiated. You can use this property instead of destinationLookup. This is not a mandatory value.


Whether the connection is configured to share subscriptions.

The default value is False.


The user for the JMS connection. This is not a mandatory value.


The password for the JMS connection. This is not a mandatory value.


The maximum number of concurrent sessions to use. This is not a mandatory value.

The default value is 15.


The transaction timeout for the session in milliseconds. This is not a mandatory value.

If not specified or 0, the property is ignored and the transactionTimeout is not overridden and the default transactionTimeout defined in the Transaction Manager is used.


Whether or not use JNDI to look up the destination.

The default value is True.


The JNDI parameters to use in the connection. Parameters are defined as name=value pairs separated by ;


Use local transaction instead of XA.

The default value is False.


Number of attempts to set up a JMS connection. It is possible that the MDB is deployed before the JMS resources are available. In that case, the resource adapter will try to set up several times until the resources are available. This applies only to inbound connections.

The default value is -1.


Interval in milliseconds between consecutive attempts to setup a JMS connection. This applies only to inbound connections.

The default value is 2000.


Whether rebalancing of inbound connections is enabled or not.

The default value is False.

4.6.3. Some Example Use Cases for Configuring MDBs

  • Use case for MDB receiving a message

    For a basic scenario when MDB receives a message, see the helloworld-mdb quickstart that is shipped with JBoss EAP.

  • Use case for MDB sending a message

    After processing the message you may need to inform other business systems or reply to the message. In this case, you can send the message from MDB as shown in the snippet below:

    import javax.annotation.Resource;
    import javax.ejb.ActivationConfigProperty;
    import javax.ejb.MessageDriven;
    import javax.inject.Inject;
    import javax.jms.JMSContext;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageListener;
    import javax.jms.Queue;
    @MessageDriven(name = "MyMDB", activationConfig = {
        @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "queue/MyMDBRequest"),
        @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
        @ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge") })
    public class MyMDB implements MessageListener {
        private JMSContext jmsContext;
        @Resource(lookup = "java:/queue/ResponseDefault")
        private Queue defaultDestination;
         * @see MessageListener#onMessage(Message)
        public void onMessage(Message rcvMessage) {
            try {
                Message response = jmsContext.createTextMessage("Response for message " + rcvMessage.getJMSMessageID());
                if (rcvMessage.getJMSReplyTo() != null) {
                    jmsContext.createProducer().send(rcvMessage.getJMSReplyTo(), response);
                } else {
                    jmsContext.createProducer().send(defaultDestination, response);
            } catch (JMSException e) {
                throw new RuntimeException(e);

    In the example above, after the MDB receives the message, it replies to either the destination specified in JMSReplyTo or the destination which is bound to the JNDI name java:/queue/ResponseDefault.

  • Use case for MDB configuring rebalancing of inbound connection

        activationConfig =
            @ActivationConfigProperty(propertyName = "destinationType",propertyValue = "javax.jms.Queue"),
            @ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = "queueA"),
            @ActivationConfigProperty(propertyName = "rebalanceConnections", propertyValue = "true")