如果我扩展DataSource类,则ctx.lookup()返回null

时间:2014-06-25 08:49:45

标签: java java-ee tomcat jndi connection-pooling

对于测试,我想手动将数据源绑定到名称。它适用于apache SharedPoolDataSource,但如果我扩展该类,则ctx.lookup()将返回null。

它与InstanceKeyObjectFactory.isCorrectClass()返回false有关。

我想要的只是记录Datasource.getConnection()

package org.foo;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameAlreadyBoundException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;
import org.apache.commons.dbcp.datasources.SharedPoolDataSource;

public class TestFactory {

    private static final String JNDINAME = "stubJs";
    private static final String JDBCURL = "jdbc:db2://localhost:50000/dbname";

    public static void main(String[] args) throws Exception {
        String jndiName = JNDINAME;
        InitialContext ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup(jndiName);
        System.out.println(ds);
    }

    static {
        Context ictx;
        try {
            DriverAdapterCPDS cpds = new DriverAdapterCPDS();
            cpds.setDriver("com.ibm.db2.jcc.DB2Driver");
            cpds.setUrl(JDBCURL);
            cpds.setUser("db2admin");
            cpds.setPassword("db2admin");

            SharedPoolDataSource tds = new SharedPoolDataSource() {};
            //SharedPoolDataSource tds = new SharedPoolDataSource();
            tds.setConnectionPoolDataSource(cpds);
            tds.setMaxActive(10);
            tds.setMaxIdle(10);
            tds.setMaxWait(10000);

            ictx = new InitialContext();

            Context ic = ictx;

            String jndiName = JNDINAME;

            int i = -1;
            while (-1 != (i = jndiName.indexOf('/', i+1))) {
                String s2 = jndiName.substring(0, i);
                try {
                    ic.createSubcontext(s2);
                } catch (NameAlreadyBoundException e) {
                    System.err.println(e);
                }
            }
            ictx.bind(jndiName, tds);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

}

0 个答案:

没有答案