我正在使用Spring MVC 3和MySQL服务器。我正在尝试将JNDI用于JDBC连接,但它返回NULL DataSource。这是一段引发空指针异常的代码。JNDI与spring mvc3集成
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
文件cantain:
<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();
}
数据源的''元素在哪里?请参阅http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html –
axtavt
2012-04-26 10:27:06
对不起,axtavt,我忘了写元素我的资源在context.xml中 –
2012-04-30 19:10:02