我正在使用 Spring MVC 3 和 MySQL 服务器。我正在尝试将 JNDI 用于 JDBC 连接,但它返回 NULL DataSource。这是抛出空指针异常的一段代码。
server.xml
文件包含:
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
context.xml
文件内容
<Resource name="jdbc/Test" auth="Container" type="javax.sql.DataSource"
maxActive="100" maxIdle="30" maxWait="10000"
username="root" password="123456" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/test"/>
web.xml
文件包含:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/Test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
despatcher-servlet.xml
文件:
<bean name="myDataSourceInJndi" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>java:comp/env/jdbc/Test</value>
</property>
</bean>
<bean name="dbConfiguration" class="com.biztree.springtest.database.DataBaseConfiguration" >
<property name="dataSource" ref="myDataSourceInJndi" />
</bean>
DataBaseConfiguration.java
package com.biztree.springtest.database;
import javax.sql.DataSource;
public class DataBaseConfiguration {
DataSource dataSource;
public DataBaseConfiguration() {
// TODO Auto-generated constructor stub
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getDataSource() {
return dataSource;
}
}
听到的是连接的代码
/* this code work throw NullPointerException */
try {
DataBaseConfiguration baseConfiguration = new DataBaseConfiguration();
DataSource ds = baseConfiguration.getDataSource();
System.out.println("ds Object : " + ds);
connection = ds.getConnection();
} catch (Exception exception) {
exception.printStackTrace();
}
但是 ds
是空的。
如果我使用下面的代码比它正常工作
/* this code work fine */
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/Test");
System.out.println("ds Object : " + ds);
connection = ds.getConnection();
} catch (Exception exception) {
exception.printStackTrace();
}
最佳答案
您需要打开 spring 的调试日志记录,和/或调试 spring 以查看它实际查找的内容,并将其与您的直接 JNDI 代码正在执行的操作进行比较。
像这样的事情也可能让你失望:
(您在 JndiObjectFactoryBean 上设置此属性,它会自动添加 comp/env 部分...检查默认值是什么并确保其设置正确)
无论如何,一旦你调试 spring 以查看它在做什么,你就能够确认。
关于java - JNDI 与 spring mvc3 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10331391/