在Spring中使用JDBC遇到了Nullpointer异常

时间:2012-11-25 13:14:56

标签: java spring

请原谅我,因为我是一名春季初学者。我跟随书中的例子,但我只是将数据库从Derby更改为MySQL。

我的主课很简单:

public class Main {

public static void main(String [] args)
{
    ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");

    VehicleDAO dao= (VehicleDAO) context.getBean("vehicleDao");
    Vehicle vehicle = new Vehicle("TEM0001", "Red", 4, 4);
    dao.insert(vehicle);
}

}

它创建了一个数据访问对象并尝试将新的Vehicle对象添加到DAO中.Garicle类非常简单,是一个包含四个字段的对象类。

将VehicleDAO类粘贴在此处:

http://pastebin.com/ekB2Rb40

我的bean文件就像:

<bean id="dataSource"
 class="org.apache.commons.dbcp.BasicDataSource">
  <property name="driverClassName"
   value="org.gjt.mm.mysql.Driver" />
   <property name="url"
   value="jdbc:mysql://localhost:3306/vehicle" />
  <property name="username" value="root" />
  <property name="password" value="3324911" />
  <property name="initialSize" value="2" />
  <property name="maxActive" value="5" />
</bean>
<bean id="vehicleDao"
  class="com.apress.springrecipes.vehicle.JdbcVehicleDao">
  <property name="dataSource" ref="dataSource" />
</bean>

正如您在上面所看到的,我总是在行

处获得空指针错误
conn= dataSource.getConnection();

所以我怀疑MySQL连接有问题,但我已经在Eclipse的类路径中包含了“mysql-connector-java-bin.jar”。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

你的二传手中有拼写错误

  public void setDataSource(DataSource datasource)
        {
                this.dataSource=dataSource;
        }

所以当Spring注入数据源时,它的值不会被保存,我想知道你的IDE是否检查了这类错误的源代码。

P.S。您不应该在我们在Spring中使用JdbcTemplate的DAO类中手动打开数据库连接。