昨天在项目中配置了一下jndi数据源。从网上搜了好多文章,介绍配置方法。
全局是这种配置方法:
在tomcat的conf文件夹下,打开context.xml在里面加入如下节点:
<Resource name="jndi/mybatis"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/appdb"
username="root"
password="123456"
maxActive="20"
maxIdle="10"
maxWait="10000"/>
然后在web.xml配置文件中配置:
<resource-ref>
<description>JNDI DataSource</description>
<res-ref-name>jndi/mybatis</res-ref-name>
<res-ref-type>javax.sql.DataSource</res-ref-type>
<res-auth>Container</res-auth>
</resource-ref>
程序中调用:
public void test() throws Exception{
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jndi/mybatis");
Connection conn = ds.getConnection();
System.out.println(conn.isClosed());
}
我在项目中使用的是这个方法,是使用工具类读取配置文件中的数据源进行使用的。我的配置是:
<Resource name="jdbc/jysy"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@10.12.1.89.111:orcl"
username="pro_test"
password="pro_test"
maxActive="20"
maxIdle="10"
maxWait="10000"/>
配置文件中写入的是这一句:
dataSource.jndiName=java:comp/env/jdbc/jysy
一开始没用过,因此我在写修改上述context.xml的时候,直接写了 :
name = "java:comp/env/jdbc/jysy" 然后启动就开始报错了。
排查到最后,发现是这个name错误, java:comp/evn 这句话的意思是:定义了一个javaee的环境变量。因此他不应该出现在resource节点的name中,在name中 只是写"jdbc/jysy"就够了。