使用JNDI的javax.naming.NoInitialContextException

时间:2012-11-07 10:35:46

标签: java jndi

我试图通过使用JNDI连接mysql。但它显示异常

javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:

请参阅我的代码:

    VendorDataSource vds = new VendorDataSource();
    vds.setServerName("localhost");
    vds.setDatabaseName("jnditest");
    vds.setDescription("The data source for inventory and personnel");

    try {
            ctx = new InitialContext();
        ctx.bind("jdbc/myds", vds);

    } catch (NamingException e1) {

        e1.printStackTrace();
    }

    try {
        ctx = new InitialContext();
        DataSource ds = (DataSource)ctx.lookup("jdbc/myds");
        Connection conn = ds.getConnection("root", "password");

    } catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

错误信息:

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.bind(Unknown Source)
    at samplemariadb.DataSourceConnectivity.main(DataSourceConnectivity.java:33)

1 个答案:

答案 0 :(得分:1)

通常你需要指定从哪里获取InitialContext(以及你将使用的jndi树的位置)

您可以通过两种方式实现:

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "<initialContextFactory>");
env.put(Context.PROVIDER_URL, "<url>");
env.put(Context.SECURITY_PRINCIPAL, "<user>");
env.put(Context.SECURITY_CREDENTIALS, "<password>");
ctx = new InitialContext(env);

或创建一个jndi.properties并将其放在类路径中:

java.naming.factory.initial=<initialContextFactory>
java.naming.provider.url=<url>
java.naming.security.principal=<user>
java.naming.security.credentials=<password>

在您的情况下,它抱怨是因为缺少INITIAL_CONTEXT_FACTORY(这取决于您使用的是哪个Java EE服务器)。

希望有所帮助