This code for a Java EE 7 message driven bean receives messages as expected, but fails to send replies, as the JMSContext is always null. What could cause the injection to fail?
I have tried different ways to inject the context, with and without the additional @JMSConnectionFactory annotation:
@JMSConnectionFactory("java:comp/DefaultJMSConnectionFactory")
or
@JMSConnectionFactory("java:/ConnectionFactory")
The latter is the value shown in the JNDI screen of the admin web interface.
package com.example.wf10mdb;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.inject.Inject;
import javax.jms.JMSConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import javax.jms.Topic;
@MessageDriven(activationConfig
= {
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
@ActivationConfigProperty(propertyName = "destination", propertyValue = "java:app/jms/topic/ExampleTopic")
})
public class ChatMessageBean implements MessageListener {
@Override
public void onMessage(Message message) {
try {
final TextMessage textMessage = (TextMessage) message;
final String question = textMessage.getText();
System.out.println(question);
if (null != question) {
switch (question) {
case "Hello World!":
respond("Hello, Test Case!");
break;
case "How are you?":
respond("I'm doing well.");
break;
case "Still spinning?":
respond("Once every day, as usual.");
break;
}
}
} catch (JMSException e) {
throw new IllegalStateException(e);
}
}
@Resource(mappedName = "java:/jms/topic/ExampleTopic")
private Topic answerTopic;
@Inject
@JMSConnectionFactory("java:/ConnectionFactory")
JMSContext context;
public void respond(String txt) {
if (context == null) {
System.out.println("context is null");
return;
}
try {
context.createProducer().send(answerTopic, txt);
} catch (Exception exc) {
exc.printStackTrace(System.out);
}
}
}