java-如何在jms中使用JNDI

我正在学习JMS在下面尝试了一个简单的示例,但它给出了错误

package pointToPoint;
import javax.naming.InitialContext;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;

public class Receiver
{
    public static void main(String[] args) throws Exception
    {
       // get the initial context
       InitialContext ctx = new InitialContext();

       // lookup the queue object
       Queue queue = (Queue) ctx.lookup("queue/queue0");

       // lookup the queue connection factory
       QueueConnectionFactory connFactory = (QueueConnectionFactory) ctx.
           lookup("queue/connectionFactory");

       // create a queue connection
       QueueConnection queueConn = connFactory.createQueueConnection();

       // create a queue session
       QueueSession queueSession = queueConn.createQueueSession(false,
           Session.AUTO_ACKNOWLEDGE);

       // create a queue receiver
       QueueReceiver queueReceiver = queueSession.createReceiver(queue);

       // start the connection
       queueConn.start();

       // receive a message
       TextMessage message = (TextMessage) queueReceiver.receive();

       // print the message
       System.out.println("received: " + message.getText());

       // close the queue connection
       queueConn.close();
    }
}

错误信息:

Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
    at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
    at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
    at javax.naming.InitialContext.lookup(Unknown Source)
    at pointToPoint.Receiver.main(Receiver.java:22)

谁能帮我这个忙.

解决方法:

答案在堆栈跟踪中.在独立应用程序中,应将环境(实现,URL等)传递给InitialContext.在像JBoss这样的J2EE容器中,您的代码将起作用.

这应该有助于:
NoInitialContextException error

上一篇:java-JDBC数据源的JNDI路径?


下一篇:java-我的代码中JNDI名称在哪里?