Adding datasource programmatically to JNDI context

2019-05-09 23:41发布

I'm trying to register a new datasource before the server starts but on lookup execution I'm getting

javax.naming.NameNotFoundException: Name [jdbc/db] is not bound in this Context. Unable to find [jdbc].

This is how I start tomcat:

    Tomcat tomcat = new Tomcat();
    //...
    ContextResource resource = new ContextResource();
    resource.setName("jdbc/db");
    resource.setAuth("Container");
    resource.setType("javax.sql.DataSource");
    resource.setScope("Sharable");
    resource.setProperty("driverClassName", "org.hsqldb.jdbc.JDBCDriver");
    resource.setProperty("url", "jdbc:hsqldb:hsql://localhost:1234/mydb1");

    tomcat.getServer().getGlobalNamingResources().addResource(resource);
    tomcat.start();
    tomcat.getServer().await();

The lookup:

    Connection conn = null;
    try {
        Context initContext = new InitialContext();
        Context envContext = (Context) initContext.lookup("java:/comp/env");
        DataSource ds = (DataSource) envContext.lookup("jdbc/db");

        conn = ds.getConnection();
        conn.createStatement()....
    } catch (Exception e) {
        e.printStackTrace();
    }

What am I missing here?

2条回答
三岁会撩人
2楼-- · 2019-05-10 00:27

Oh well i figured it out! Instead of adding it in the GlobalNamingResources

tomcat.getServer().getGlobalNamingResources().addResource(resource);

I added it in the NamingResources

Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
//...
rootCtx.getNamingResources().addResource(resource);

and it works!

If someone can tell me the difference between globalNamingResources and (local)NamingResources and how to lookup a globalNamingResource then please leave me a comment!

查看更多
仙女界的扛把子
3楼-- · 2019-05-10 00:29

You don't show us how you look up the JNDI resource. However, in any case the full JNDI name to your resource is java:comp/env/jdbc/db i.e. that's what you need for lookup.

There's further reading here: https://stackoverflow.com/a/4099163/131929

查看更多
登录 后发表回答