package com.accp;import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class StudentDAO extends HibernateDaoSupport implements
IMStudentDAO {
 private HibernateTemplate ht;
public StudentDAO(){
ht=this.getHibernateTemplate();
}
public void save(Student stu){

ht.save(stu);
}当调用时
public static void main(String[] args) {
ApplicationContext context=new  ClassPathXmlApplicationContext("applicationContext.xml");
IMStudentDAO sdao=(IMStudentDAO)context.getBean("StudentDAO");
Student stu=(Student)context.getBean("stu");
stu.setName("bb");
sdao.save(stu);
System.out.println("ok");
}
出错
Exception in thread "main" java.lang.NullPointerException
at com.accp.StudentDAO.save(StudentDAO.java:29)
at com.accp.test.main(test.java:26)
如果这样写
public class StudentDAO extends HibernateDaoSupport implements
IMStudentDAO {
public void save(Student stu){
HibernateTemplate ht=this.getHibernateTemplate();;
ht.save(stu);
}调用就没有问题
谁能给我说说是为什么

解决方案 »

  1.   

    构造时HibernateDaoSupport里的hibernateTemplate还没初始化,是null。有兴趣去读读源码看看
      

  2.   

    public StudentDAO(){
    ht=this.getHibernateTemplate();
    }
    这种写法是在构造方法中对ht变量赋值,因为这时StudentDAO这个类的实例是正在过程中,也就是StudentDAO的本身没有构造好,所以这时调用它的一个方法getHibernateTemplate当然会出现Nullpoint的异常,而
    public void save(Student stu){
    HibernateTemplate ht=this.getHibernateTemplate();
    ht.save(stu);
    }
    在构造方法被执行后在执行,所以getHibernateTemplate是可以使用的。
      

  3.   

    在sdao.save(stu); 时;public void save(Student stu){ht.save(stu);
    }save()中的ht 还是private HibernateTemplate ht;;此时并没有对ht进行构造;因为你sdao
    只是StudentDAO的类的对象;
      

  4.   

    直接 getHibernateTemplate().save(stu)