以编程方式将数据源添加到嵌入式tomcat 7中的JNDI上下文 [英] 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:名称[jdbc / db]未绑定在此Context中。无法找到[jdbc]。
javax.naming.NameNotFoundException: Name [jdbc/db] is not bound in this Context. Unable to find [jdbc].
这就是我启动tomcat的方式:
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();
查询:
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();
}
我在这里缺少什么?
推荐答案
哦,我想通了!而不是在GlobalNamingResources中添加它
Oh well i figured it out! Instead of adding it in the GlobalNamingResources
tomcat.getServer().getGlobalNamingResources().addResource(resource);
我在NamingResources中添加了它
I added it in the NamingResources
Context rootCtx = tomcat.addContext("", base.getAbsolutePath());
//...
rootCtx.getNamingResources().addResource(resource);
它有效!
如果有人可以告诉我globalNamingResources和(local)NamingResources之间的区别以及如何查找globalNamingResource然后请给我留言!
If someone can tell me the difference between globalNamingResources and (local)NamingResources and how to lookup a globalNamingResource then please leave me a comment!
这篇关于以编程方式将数据源添加到嵌入式tomcat 7中的JNDI上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!