Michael Remijan
Michael Remijan

Reputation: 707

Payara 5 @JMSConnectionFactory fails to inject when using @Stateless bean

I am testing out some JMS work on Paraya 5. Specifically 5.181. Below is the code for my simple Stateless bean. @JMSConnectionFactory fails! the JMSContext context variable is always null. However @Resource(lookup = "jms/HelloWorldConnectionFactory") succeeds...Any thoughts as to why? I'd prefer to use JMSContext.

@Stateless
public class HelloWorldMessageSender {

    @JMSConnectionFactory("jms/HelloWorldConnectionFactory")
    protected JMSContext context;

    @Resource(lookup = "jms/HelloWorldConnectionFactory")
    protected ConnectionFactory connectionFactory;

    @Resource(lookup = "jms/HelloWorldQueue")
    protected Queue queue;

    public String send() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS");
        String txt = String.format("Hello world message %s", sdf.format(new Date()));
        if (context != null) {
            System.out.printf("Use JMSContext to produce%n");
            context.createProducer().send(queue, txt);
        }
        if (connectionFactory != null) {
            System.out.printf("Use ConnectionFactory to produce%n");
            try (
                Connection connection = connectionFactory.createConnection();
                Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                MessageProducer producer = session.createProducer(queue);
            ) {
                TextMessage message = session.createTextMessage();
                message.setText(txt);
                producer.send(message);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return txt;
    }
}

Just as a note, the @Stateless bean is being used inside of a JSF @Named bean. I'm using simple CDI injection to get the @Stateless bean, like this:

@Named(value = "helloWorldMessageController")
@RequestScoped
public class HelloWorldMessageController {

    @Inject
    protected HelloWorldMessageSender sender;

    // ....
}

Upvotes: 3

Views: 1122

Answers (1)

Ondro Mihályi
Ondro Mihályi

Reputation: 7710

The annotation @JMSConnectionFactory has to be used with @Inject otherwise it doesn't have any effect. It just adds meta data for injection but doesn't cause any injection to happen.

It's clear from the example in the JMS 2.0 specification PDF:

@Inject @JMSConnectionFactory("jms/connectionFactory") private JMSContext context;

On the other hand, @Resource annotation is enough for injection because they are processed by the EJB container which handles them as injection point. So you should either use a single @Resource annotation or both @Inject and @JMSConnectionFactory together.

Upvotes: 6

Related Questions