Java 命名和目录接口(JNDI)是 Java 平台的一部分,为基于 Java 技术的应用程序提供与多个命名和目录服务的统一接口。您可以使用此行业标准构建功能强大且支持目录的可移植应用程序。
在应用程序服务器中部署应用程序时,容器将为您设置 JNDI 树。但是,如果您正在编写框架或只是独立应用程序,则以下示例将向您展示如何构造和绑定对 DBCP 数据源的引用。
以下示例使用 sun 文件系统 JNDI 服务提供程序。
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
System.setProperty(Context.PROVIDER_URL, "file:///tmp");
InitialContext ic = new InitialContext();
// 构造 BasicDataSource
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("org.apache.commons.dbcp2.TesterDriver");
bds.setUrl("jdbc:apache:commons:testdriver");
bds.setUsername("userName");
bds.setPassword("password");
ic.rebind("jdbc/basic", bds);
// 使用
InitialContext ic2 = new InitialContext();
DataSource ds = (DataSource) ic2.lookup("jdbc/basic");
assertNotNull(ds);
Connection conn = ds.getConnection();
assertNotNull(conn);
conn.close();System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
System.setProperty(Context.PROVIDER_URL, "file:///tmp");
InitialContext ic = new InitialContext();
// 构造 DriverAdapterCPDS 参考
Reference cpdsRef = new Reference("org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS",
"org.apache.commons.dbcp2.cpdsadapter.DriverAdapterCPDS", null);
cpdsRef.add(new StringRefAddr("driver", "org.apache.commons.dbcp2.TesterDriver"));
cpdsRef.add(new StringRefAddr("url", "jdbc:apache:commons:testdriver"));
cpdsRef.add(new StringRefAddr("user", "foo"));
cpdsRef.add(new StringRefAddr("password", "bar"));
ic.rebind("jdbc/cpds", cpdsRef);
// 构造 PerUserPoolDataSource 参考
Reference ref = new Reference("org.apache.commons.dbcp2.datasources.PerUserPoolDataSource",
"org.apache.commons.dbcp2.datasources.PerUserPoolDataSourceFactory", null);
ref.add(new StringRefAddr("dataSourceName", "jdbc/cpds"));
ref.add(new StringRefAddr("defaultMaxTotal", "100"));
ref.add(new StringRefAddr("defaultMaxIdle", "30"));
ref.add(new StringRefAddr("defaultMaxWaitMillis", "10000"));
ic.rebind("jdbc/peruser", ref);
// 使用
InitialContext ic2 = new InitialContext();
DataSource ds = (DataSource) ic2.lookup("jdbc/peruser");
assertNotNull(ds);
Connection conn = ds.getConnection("foo","bar");
assertNotNull(conn);
conn.close();