独立Java程序中的Initialcontext [英] Initialcontext in a standalone Java program

查看:494
本文介绍了独立Java程序中的Initialcontext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JNDI创建tomcat连接池。它在Web应用程序中运行良好。我相信InitialContext是由tomcat服务器提供的。

I'm using a JNDI for creating tomcat connection pool. It works great in a web application. I believe the InitialContext is provided by the tomcat server.

Context initContext  = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
dataSource = (DataSource)envContext.lookup("jdbc/testdb");

但是当我尝试从独立的Java程序调用相同的实用程序时,initContext对象为null。我如何显式提供Context对象期望的所有必要属性。

But when I try to call the same utility from a standalone Java program, the initContext object is null. How can I explicitly provide all the necessary properties that Context object is expecting.


错误:javax.naming.NoInitialContextException:需要指定类
环境或系统属性中的名称,或applet参数,或应用程序资源文件中的
:java.naming.factory.initial

Error : 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


推荐答案

您还可以创建自己的自定义上下文。

You could also create your own custom context.

LocalContext ctx = LocalContextFactory.createLocalContext();
ctx.addDataSource("jdbc/testdb", driverName, url, usr, pwd);

参见 在本地运行使用Application Server数据源的Bean 以获取更多详细信息。

See Running Beans Locally that use Application Server Data Sources for more details.

UPDATE

您可以使用类 org.springframework.mock.jndi.SimpleNamingContextBuilder 春天例如:

You can use the class org.springframework.mock.jndi.SimpleNamingContextBuilder of Spring. e.g.:


  • 设置:

SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
builder.bind("jdbc/Oracle", ods);
builder.activate();


  • 使用:

    DataSource ds = InitialContext.doLookup("jdbc/Oracle");
    


  • 这篇关于独立Java程序中的Initialcontext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆