我想在Spring的測試項目中定義JNDI DB連接。我用Spring Roo引導了這個項目,因此是Maven化的。這裏是Roo的腳本供參考(Roo的1.2.1)NameNotFoundException:在此上下文中未綁定名稱jdbc
project --topLevelPackage org.obliquid.cpool
jpa setup --database MYSQL --provider HIBERNATE --jndiDataSource /jdbc/cpool
web mvc setup
entity jpa --class org.obliquid.cpool.entity.Person
field string --fieldName name
web mvc scaffold --class ~.entity.Person
web mvc all --package ~.web
在src/main/resources/META-INF/spring/applicationContext.xml
我以下(由小豆創建):我創建src/main/resources/META-INF/context.xml
有以下內容
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
...
<jee:jndi-lookup id="dataSource" jndi-name="/jdbc/cpool" resource-ref="true"/>
...
:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/myapp" docBase="cpool" reloadable="true" debug="1">
<Resource name = "jdbc/cpool"
auth = "Container"
type = "javax.sql.DataSource"
username = "dbusername"
password = "dbpassword"
driverClassName = "com.mysql.jdbc.Driver"
url = "jdbc:mysql://localhost:3306/dbname?DateTimeBehavior=convertToNull&characterEncoding=UTF-8"
maxActive = "100"
maxIdle = "4"
maxWait = "20000"
removeAbandoned = "true"
removeAbandonedTimeout="600"
logAbandoned="true"/>
</Context>
然而,當我嘗試給Tomcat 7.0運行應用程序,我得到以下錯誤:
ERROR org.springframework.web.context.ContextLoader - Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource': Invocation of init method failed; nested exception is javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
如何正確定義數據源?
啊啊!錯誤的'META-INF'文件夾!所以我把'context.xml'放在'src/main/webapp/META-INF'中,並將它打包到war文件的'/ META-INF'文件夾中,一切正常,非常感謝! – stivlo 2012-02-19 16:44:59
如果必須在碼頭部署戰爭,這是否行得通? – Sikorski 2012-07-31 13:38:43
@Sikorski:沒有。 context.xml是一個Tomcat專有文件。 – 2012-07-31 13:53:51