NullPointer in Glassfish when inject JMS @Resource

2019-07-23 17:36发布

问题:

I'm trying to write a very simple JMS app to deploy on Glassfish as a means of getting my head around JMS.

In the class the sends the message I have the following:

    @Resource(mappedName="jms/MyConnectionFactory")
    public static QueueConnectionFactory factory;

    @Resource(mappedName="jms/MyQueue")
    public static Queue queue;

This results in a NullPointer, the first time I try and access the factory. If I try and look up the object using JNDI, however, it works. This class is simply a POJO which is accessed by a JSP running in a simple web app.

Is it because it is a POJO and not, for example, a servlet that this is failing?

I had assumed that the fact it was deployed and running inside Glassfish would be enough - obviously I am wrong...

回答1:

Use name instead of mappedName. name is the JNDI name, mappedName is something else. See the API doc

@Resource(name="jms/MyConnectionFactory")
public static QueueConnectionFactory factory;

I just read that your class is a simple POJO. Your class must be some bean that is managed by a container in order to make these annotations work. Like @Stateless, @Stateful, @Singleton.