我正在尝试使用Spring在测试项目中定义JNDI数据库连接。我用Spring Roo引导了这个项目,因此是Mavenized。这是Roo脚本供参考(Roo 1.2.1)
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
我有以下内容(由Roo创建):
<?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"/>
...
我使用以下内容创建了src/main/resources/META-INF/context.xml
:
<?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中运行该应用程序时,出现以下错误:
错误org.springframework.web.context.ContextLoader - 上下文初始化失败 org.springframework.beans.factory.BeanCreationException:创建名为'dataSource'的bean时出错:init方法的调用失败;嵌套异常是javax.naming.NameNotFoundException:名称jdbc未绑定在此Context中
如何正确定义数据源?
答案 0 :(得分:11)
context.xml文件必须位于 war 文件的META-INF目录中。它不能在classes目录或jar文件中。
将META-INF目录和context.xml放在源文件夹树中包含webapp根目录的目录中。