以编程方式将数据源添加到嵌入式tomcat 7中的JNDI上下文

ali*_*ali 4 java tomcat jndi datasource jdbc

我正在尝试在服务器启动之前注册一个新的数据源,但是我正在查找执行的查找

javax.naming.NameNotFoundException:名称[jdbc/db]未绑定在此Context中.无法找到[jdbc].

这是我启动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();
Run Code Online (Sandbox Code Playgroud)

查找:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

ali*_*ali 5

哦,我想通了!而不是在GlobalNamingResources中添加它

tomcat.getServer().getGlobalNamingResources().addResource(resource);
Run Code Online (Sandbox Code Playgroud)

我在NamingResources中添加了它

Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
//...
rootCtx.getNamingResources().addResource(resource);
Run Code Online (Sandbox Code Playgroud)

它的工作原理!

如果有人能告诉我globalNamingResources和(本地)NamingResources之间的区别以及如何查找globalNamingResource,那么请给我留言!


Mar*_*tör 0

您没有向我们展示您如何查找 JNDI 资源。但是,无论如何,您的资源的完整 JNDI 名称就是java:comp/env/jdbc/db您查找所需的名称。

这里有进一步阅读:/sf/answers/286941441/