我正在尝试使用 Spring 在测试项目中定义 JNDI DB 连接。我已经使用 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&amp;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



我应该怎么做才能正确定义数据源?

请您参考如下方法:

context.xml 文件必须在 的 META-INF 目录中。 war 文件。它不能位于 classes 目录或 jar 文件中。

将带有 context.xml 的 META-INF 目录放在源文件夹树中包含 web 应用程序根目录的目录中。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!