Java EE @Resource注释,查找,NullPointerException

时间:2014-05-11 20:44:39

标签: java nullpointerexception resources annotations

我正在学习一本名为Beginning Java EE 7的书,但我没能运行本书中的一个例子。当我运行下面的代码时,输​​出是:

无限循环。等待消息......

线程中的异常" main" org.agoncal.book.javaee7.chapter13.ex05.Consumer05.main(Consumer05.java:34)的java.lang.NullPointerException

我使用了if语句来检查对象" connectionFactory"和"队列"我发现它们都是空的。有谁知道如何解决这个错误?

源代码可在此处找到:https://github.com/agoncal/agoncal-book-javaee7

第13章,第13章 - 样本。

package org.agoncal.book.javaee7.chapter13.ex05;

import javax.annotation.Resource;
import javax.jms.ConnectionFactory;
import javax.jms.JMSContext;
import javax.jms.Queue;

/**
 * @author Antonio Goncalves
 *         APress Book - Beginning Java EE 7 with Glassfish 4
 *         http://www.apress.com/
 *         http://www.antoniogoncalves.org
 *         --
 */
public class Consumer05 {

  // ======================================
  // =             Attributes             =
  // ======================================

  @Resource(lookup = "jms/javaee7/ConnectionFactory")
  private static ConnectionFactory connectionFactory;
  @Resource(lookup = "jms/javaee7/Queue")
  private static Queue queue;

  // ======================================
  // =           Public Methods           =
  // ======================================

  public static void main(String[] args) {

    // Loops to receive the messages
    System.out.println("\nInfinite loop. Waiting for a message...");
    try (JMSContext context = connectionFactory.createContext()) {
      while (true) {
        String message = context.createConsumer(queue).receiveBody(String.class);
        System.out.println("Message received: " + message);
      }
    }
  }
}

0 个答案:

没有答案