Resources injection doesn't work when running

2019-06-24 06:04发布

问题:

I want to run the jms tutorial files in eclipse. I have configured glassfish properly and added the jms resources. It works ok if I run it in netbeans.

I created an "application client project" in eclipse.

Here is where the resources get injected:

 @Resource(mappedName = "jms/ConnectionFactory")
 private static ConnectionFactory connectionFactory;
 @Resource(mappedName = "jms/Queue")
 private static Queue queue;
 @Resource(mappedName = "jms/Topic")
 private static Topic topic;

Then, when it gets here:

connection = connectionFactory.createConnection();

I get a NullPointerException. For some reason it doesn't get the resources from the server so they are null.

It works if I build the project in eclipse and then run it from a command line using appclient:

 appclient Producer topic 4

It says here http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jst.j2ee.doc.user%2Ftopics%2Fcjappcliproj.html that:

An application client module is used to contain a full-function client Java™ application (non Web-based) that connects to and uses the Java EE resources defined in your server. When you place the client code in an application client module instead of a simple JAR file, the application client benefits from the server's resources (it does not need to re-specify the class path to Java EE and server JAR files) as well as from easier JNDI lookup (the client container fills in the initial context and other parameters).

So it seems that I am on the right track, but maybe I am missing some eclipse configuration.

回答1:

As you've already noticed, if you run your Application in standalone mode you will not be able to access servers resources, this is by design. You need to use Glassfish appclient (or similar tools for other application servers) in order to run a Java EE Client App. Heres another thread that may help you configure your project to run correctly: eclipse howto start a application client on java ee glassfish appl srv.