带有mysql DataSource的javax.naming.NoInitialContextException

时间:2013-11-16 08:43:11

标签: java mysql datasource jndi

尝试连接MySQL数据库

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); 我被卡住,任何人都可以帮助我吗?感谢。

1 个答案:

答案 0 :(得分:2)

这是因为MysqlDataSource没有实现javax.naming.spi.InitialContextFactory接口。

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

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;
}