我在 applicationContext.xml 中使用 spring 的 BasicDataSource 如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-autowire="byType">
<bean id="datasource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/school" />
<property name="username" value="root" />
<property name="password" value="" />
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>
</beans>
当我在控制器中使用这个bean时,如下所示:
package admin.controller;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.inject.*;
@Controller
public class Welcome {
@Inject
BasicDataSource datasource;
private static final String WELCOME_PAGE = "welcome";
@RequestMapping("/")
public String welcome(ModelMap model){
Connection con=null;
PreparedStatement stmt =null;
String testQuery = "INSERT INTO ADMIN(ID,USER_NAME,PASSWORD,FIRST_NAME,LAST_NAME) VALUES(?,?,?,?,?)";
try {
con = datasource.getConnection();
stmt = con.prepareStatement(testQuery);
stmt.setInt(1, 4);
stmt.setString(2, "ij");
stmt.setString(3, "kl");
stmt.setString(4, "mn");
stmt.setString(5, "op");
stmt.execute();
//con.commit();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
try {
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return WELCOME_PAGE;
}
}
然后它给了我一个空指针异常: datasource.getConnection();
连接详细信息是 100% 正确的,因为当我在控制器内创建 BasicDatasource 的新实例并使用其设置器方法(例如:datasource.setDriverClassName 等)添加详细信息时,它会连接到数据库并毫无问题地执行查询。但是当我想从应用程序上下文中使用 bean 时,它给了我一个空指针异常。