本文介绍了带有mysql DataSource的javax.naming.NoInitialContextException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试连接到MySQL数据库

Trying to connect to a MySQL database

MysqlDataSource mysqlDs = new MysqlDataSource();
Properties prop = new Properties();
String mysqlDataSourceDriver = "com.mysql.jdbc.jdbc2.optional.MysqlDataSource";
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, mysqlDataSourceDriver);
properties.put(Context.PROVIDER_URL , "jdbc:mysql://localhost:3306/database");
Context ctx = new InitialContext(prop);
ctx.bind("jdbc/wczasy", mysqlDs);

堆栈跟踪:

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(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344)
at javax.naming.InitialContext.bind(InitialContext.java:419)
at src.wczasy.database.Connector.connect(Connector.java:53)
at src.wczasy.Wczasy.main(Wczasy.java:10)

由行引起:ctx.bind( jdbc / wczasy,mysqlDs);
我被卡住了,有人可以帮帮我吗?谢谢。

Caused by line: ctx.bind("jdbc/wczasy", mysqlDs);I am stuck, can anyone help me out? Thanks.

推荐答案

这是因为 MysqlDataSource 未实现 javax.naming.spi.InitialContextFactory interface。

This is because MysqlDataSource is not implementing javax.naming.spi.InitialContextFactory interface.

如果您不在容器中,可以使用rmi注册表。类似于:

If you are not in a container you can use rmi registry. Something like:

try{
  startRegistry();
  InitialContext context = createContext();
  MysqlDataSource mysqlDs = new MysqlDataSource();
  context.rebind("jdbc/wczasy", mysqlDs);
} catch (Exception e) {
  System.out.println("Error while binding: " + e.getMessage());
  e.printStackTrace();
}


private static void startRegistry() throws RemoteException {
  LocateRegistry.createRegistry(1099);
  System.out.println("RMI registry ready.");
}

private static InitialContext createContext() throws NamingException {
  Properties env = new Properties();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.rmi.registry.RegistryContextFactory");
  env.put(Context.PROVIDER_URL, "rmi://localhost:1099");
  InitialContext context = new InitialContext(env);
  return context;
}

这篇关于带有mysql DataSource的javax.naming.NoInitialContextException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:10