// 在此输入java代码/*
* 数据源管理器,可以管理多个数据源
* 提高 JNDI 查找的速度
*/package comm.ds;
import java.util.HashMap;
import java.util.Map;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
publicclass DataSourceManager {
privatestatic DataSourceManager instance;
private Map dataSources;
private Context context;
// This is private, and can't be instantiated directlyprivate DataSourceManager() throws NamingException {
dataSources = new HashMap();
// Get the context for caching purposes
context = new InitialContext();
/**
* In non-J2EE applications, you might need to load up
* a properties file and get this context manually. I've
* kept this simple for demonstration purposes.
*/
}
publicstatic DataSourceManager getInstance() throws NamingException {
// Not completely thread-safe, but good enough // (see note in article)if (instance == null) {
instance = new DataSourceManager();
}
return instance;
}
public DataSource lookup(String jndiName)
throws NamingException {
// See if we already have this interface cached
DataSource ds = (DataSource) dataSources.get(jndiName);
// If not, look up with the supplied JNDI nameif (ds == null) {
ds =(DataSource) context.lookup(jndiName);
// If this is a new ref, save for caching purposes
dataSources.put(jndiName, ds);
}
return ds;
}
}
<p>