我正在使用 Spring MVC 3 和 MySQL 服务器。我正在尝试将 JNDI 用于 JDBC 连接,但它返回 NULL 数据源。这是引发空指针异常的一段代码。
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();
}