// This is private, and can't be instantiated directly private 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 name if (ds == null) { ds =(DataSource) context.lookup(jndiName);
// If this is a new ref, save for caching purposes dataSources.put(jndiName, ds); } return ds; } }
kitta
2003-10-06 04:36
求教,按楼上所述方法,我在需要连接时应使用下面的代码:
Connection con = null; con = DataSourceManager.getInstance().lookup("java:comp/env/jdbc/...").getConnection(); if ( null == con ) ...