UserDaoImpl类
public class UserDaoImpl extends HibernateDaoSupport implements UserDao{
@Override
public User findByNameAndPassword(String username, String password) {
System.out.println(getHibernateTemplate());
List<User> list = getHibernateTemplate().find("from User u where u.username = ? and u.password = ?", username,password);
//System.out.println(list.get(0).getUsername());
return list.get(0);
}
}
UserserviceImpl类
public class UserServiceImpl implements UserService {
@Override
public boolean login(String username, String password) {
User user = new User();
UserDao userDao = (UserDao) new UserDaoImpl();
user = userDao.findByNameAndPassword(username, password);
if(user!= null) {
return true;
}
return false;
}
}
刚开始以为是applicationContext.xml文件中配置出错了,后来经检查配置无误。最后发现UserServiceImpl类使用UserDaoImpl类时不是IOC注入的而是new 了一个UserDaoImpl
解决方案:注入UserDaoImpl
修改后的代码为
public class UserServiceImpl implements UserService {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public boolean login(String username, String password) {
User user = new User();
//UserDao userDao = (UserDao) new UserDaoImpl();
user = userDao.findByNameAndPassword(username, password);
if(user!= null) {
return true;
}
return false;
}
}
总结:当我们的DAO类继承了HibernateDaoSupport类后,程序运行会后发现getHibernateTemplate()为null,那么就说明我们写的DAO类不是IOC注入的而是new了一个。