Java EE Injected JMSContext Example

This example shows you how to inject a JMSContext into an MDB and use it to send a reply to a JMS Client

Wildfly configuration

The example leverages the JBoss Arquillian framework to run an Wildfly 8 instance and deploy the MDB.

Example step-by-step

download The latest Wildfly 8 from here and install.

set the JBOSS_HOME property to point to the WildFly install directory

To run the example simply type mvn testfrom the example directory

  1. Firstly in the MDB we inject the JMSContext. This will use the Default Connection Factory configured.
  2.            
                   @Inject
                   javax.jms.JMSContext context;
    
              
  3. We then map the reply queue as a resource.
  4.            
                   @Resource(mappedName = "java:/queue/replyQueue")
                   Queue replyQueue;
            
  5. First we need to get an initial context so we can look-up the JMS connection factory and destination objects from JNDI.
  6.            
                   final Properties env = new Properties();
    
                   env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    
                   env.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
    
                   initialContext = new InitialContext(env);
    
               
            
  7. We look up the JMS queue object from JNDI
  8.            Queue queue = (Queue)initialContext.lookup("jms/queues/testQueue");
            
  9. We look up the JMS connection factory object from JNDI
  10.            ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("jms/RemoteConnectionFactory");
            
  11. We create a JMSContext inside the try-with-resource block so it auto closes
  12.            
                   try
                   (
                      // Step 6.Create a JMS Connection inside the try-with-resource block so it will auto close
                      JMSContext context = cf.createContext("guest", "password")
                   )
               
            
  13. We create a JMS Producer and send a String as a message.
  14.            context.createProducer().send(queue, "This is a text message");
            
  15. We start the context so we can receive messages.
  16.            context.start();
            
  17. We look up the reply queue.
  18.           Queue replyQueue = (Queue)initialContext.lookup("jms/queues/replyQueue");
           
  19. We receive the body, as a String, of the reply message.
  20.             String text = context.createConsumer(replyQueue).receiveBody(String.class);
            
  21. And finally, close the initial context.
  22.            finally
               {
                  if (initialContext != null)
                  {
                    initialContext.close();
                  }
               }