JBoss/Wildfly: Setting a custom resource adapter for an MDB

How do you configure a Message-Driven Bean (MDB) to use a different resource adapter/connection factory from the default one?

This can be done in one of two ways.

This assumes that you’ve already defined a connection factory in your JBoss/Wildfly config, e.g.:

<pooled-connection-factory name="my-connection-factory"
    entries="java:/jms/myConnectionFactory"
    user="..." password="..." connectors="..."/>

Using annotations

Annotate your MDB class with the JBoss-specific @ResourceAdapter annotation, specifying the name of the resource adapter:

import javax.jms.MessageListener;
import org.jboss.ejb3.annotation.ResourceAdapter;

@ResourceAdapter("my-connection-factory")
@MessageDriven(name = "HelloWorldQueueMDB", activationConfig = { ... })
public class HelloWorldQueueMDB implements MessageListener {

  //...

}

If you need to send messages, just inject the connection factory, looking it up using its JNDI name:

import javax.inject.Inject;
import javax.jms.JMSConnectionFactory;

public class MyClass {

  @Inject
  @JMSConnectionFactory("java:/jms/myConnectionFactory")
  private JMSContext context;

  //...
}

Using XML config

Alternatively, to avoid changing the code, you can set this in META-INF/jboss-ejb3.xml:

<?xml version="1.1" encoding="UTF-8"?>
<jboss:ejb-jar xmlns:jboss="http://www.jboss.com/xml/ns/javaee"
               xmlns="http://java.sun.com/xml/ns/javaee"
               xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
               xmlns:mdb="urn:resource-adapter-binding"
               xsi:schemaLocation="http://www.jboss.com/xml/ns/javaee http://www.jboss.org/j2ee/schema/jboss-ejb3-2_0.xsd http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">

  <enterprise-beans>
    <message-driven>
      <ejb-name>YourEJBName</ejb-name>
      <activation-config>
          <activation-config-property>...</activation-config-property>
          <activation-config-property>...</activation-config-property>
      </activation-config>
      <resource-ref>
        <res-ref-name>jms/YourConnectionFactoryRefName</res-ref-name>
        <res-type>javax.jms.ConnectionFactory</res-type>
        <jndi-name>java:/jms/myConnectionFactory</jndi-name>
      </resource-ref>
      ...
    </message-driven>
  </enterprise-beans>
  ...

  <assembly-descriptor>
    <mdb:resource-adapter-binding>
      <ejb-name>YourEJBName</ejb-name>
      <mdb:resource-adapter-name>my-connection-factory</mdb:resource-adapter-name>
    </mdb:resource-adapter-binding>
  </assembly-descriptor>

</jboss:ejb-jar>