javax.naming.NoInitialContextException com o mysql DataSource

Tentando se conectar a um database 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); 

E o stacktrace:

 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) 

Causado por linha: ctx.bind (“jdbc / wczasy”, mysqlDs); Eu estou preso, alguém pode me ajudar? Obrigado.

Isso ocorre porque o MysqlDataSource não está implementando a interface javax.naming.spi.InitialContextFactory .

Se você não estiver em um contêiner, poderá usar o registro rmi. Algo como:

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