简体   繁体   中英

Adding datasource programmatically to JNDI context in embedded tomcat 7

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?

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!

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 ie that's what you need for lookup.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM