以下是具体配置的步骤:
1.首先配置Tomcat下的jndi数据源。具体存放目录apache-tomcat-7.0.59\conf\Catalina\localhost 下
osh.xml
<?xml version='1.0' encoding='utf-8'?> <Context docBase="G:\sbwork\oshome\WebContent" reloadable="false" path="/osh"> <Resource name="jdbc/osh" auth="Container" type="javax.sql.DataSource" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST =(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=orcl)(SERVER=DEDICATED)))" validationQuery="select 0 from DUAL" username="olay" password="123456" maxActive="100" maxIdle="50" maxWait="10000" removeAbandoned="true" removeAbandonedTimeout="60"/> </Context>
(2)在tomcat的安装文件中lib目录下放入数据库驱动jar。
(3)spring的applicationContext.xml中配置datasource:
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/osh</value> </property> </bean>
注意Vlaue属性中必须加入java:comp/env,后面才是servers中的Resource 的name
(4)web.xml(这一步在eclipse项目要配上,不然找不到数据源)
<resource-ref> <description>Oracle Connection</description> <res-ref-name>jdbc/osh</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
同样的配置,同样的方法。Myeclipse项目启动正常,但是eclipse项目启动报错,错误入下:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘OSHDatasource‘ defined in ServletContext resource [/osh/config/osh-servlet.xml]: Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name [jdbc/osh] is not bound in this Context. Unable to find [jdbc].
错误很明显是找不到jdbc/osh,导致获取不到数据源。 很郁闷的是myclipse下没问题。纠结了好久,终于找到问题所在。 Eclipse环境下在不到tomcat的jndi数据源。 因此要在web.xml文件加上以下代码
<resource-ref> <description>Oracle Connection</description> <res-ref-name>jdbc/osh</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref>
原文地址:http://blog.csdn.net/zhixinhuacom/article/details/46496193