|
jndi一般是由容器提供,或是启动第三方服务jar包启动。
由于我在使用jetty作为内嵌服务器快速开发时需要使用jndi提供datasource来连接数据库,于是就研究了下,自己简单实现提供一个jndi服务
使用以下代码就行了。想要使用jndi就启动init方法
class MyContextBuild implements InitialContextFactoryBuilder {
private static HashMap<String, Object> map = new HashMap<String, Object>();
public static void init() {
try {
NamingManager.setInitialContextFactoryBuilder(new MyContextBuild());
} catch (NamingException e) {
e.printStackTrace();
}
}
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
return new MyContextFactory();
}
public class MyContextFactory implements InitialContextFactory {
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
return new MyContext();
}
}
public class MyContext extends InitialContext {
public MyContext() throws NamingException {
super();
}
@Override
public void unbind(String name) throws NamingException {
map.remove(name);
}
@Override
public Object lookup(String name) throws NamingException {
return map.get(name);
}
@Override
public void bind(String name, Object obj) throws NamingException {
map.put(name, obj);
}
}
}
在启动jetty时顺便启动一下自己的jndi,搞定
public static void main(String[] args) throws Exception {
MyContextBuild.init();
Context context = new InitialContext();
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setDatabaseName(DATASOURCE_DATABASE);
dataSource.setPortNumber(DATASOURCE_PORT);
dataSource.setUser(DATASOURCE_USERNAME);
dataSource.setPassword(DATASOURCE_PASSWORD);
dataSource.setEncoding(DATASOURCE_ENCODEING);
String dataSourcePath = null;
for (String url : DATASOURCE_URL) {
try {
dataSource.setServerName(url);
dataSource.setConnectTimeout(500);
dataSource.getConnection().close();
dataSourcePath = url;
break;
} catch (Exception e) {
}
}
context.bind(JNDI_NAME, dataSource);
Server server = new Server(port);
WebAppContext webContext = new WebAppContext(contenxtFileName, contextPath);
webContext.setClassLoader(Thread.currentThread().getContextClassLoader());
server.setHandler(webContext);
server.setStopAtShutdown(true);
server.start();
server.join();
} |
|