spring+struts+hibernate
用spring容器注入userManager和userDao,在其他类中需要调用UserManagerImpl中的方法时,直接
new UserManagerImpl().totalUsers()时抛出
空指针异常,但是在UserRegisterAction类中可通过userManager正常访问。各位大虾帮帮我吧!!!部分代码如下:
@Component("userManager")
public class UserManagerImpl implements UserManager {
private UserDao userDao;
public UserDao getUserDao() {
return userDao;
}
@Resource
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public boolean exists(User u) throws Exception {
return userDao.checkUserIsExistedByName(u.getUser_name());
}
public boolean correct(User u) throws Exception{
return userDao.checkUserIsCorrectByNameAndPassword(u.getUser_name(), u.getPassword());
}
public void add(User u) throws Exception {
userDao.save(u);
}
public List<User> getAllUsers() throws Exception {
return userDao.getAllUsers();
}
public User loadById(int id) throws Exception {
return userDao.loadById(id);
}
public int totalUsers() throws Exception {
return userDao.totalUsers();
}
}
@Component(value = "userDao")
public class UserDaoImpl implements UserDao {
private HibernateTemplate hibernateTemplate;
public void save(User u) {
hibernateTemplate.save(u);
}
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
}
@Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public boolean checkUserIsExistedByName(String username) {
List<User> users = hibernateTemplate
.find("from User u where u.user_name ='" + username + "'");
if (users != null && users.size() > 0)
return true;
return false;
}
public boolean checkUserIsCorrectByNameAndPassword(String username, String password) {
List<User> users = hibernateTemplate
.find("from User u where u.user_name ='" + username
+ "' and u.password = '" + password + "'");
if (users != null && users.size() > 0)
return true;
return false;
}
public List<User> getAllUsers(){
List<User> users = (List<User>)hibernateTemplate.find("from User");
return users;
}
public int totalUsers() {
return hibernateTemplate.loadAll(User.class).size();
}
public User loadById(int id) {
User users = (User)hibernateTemplate.load(User.class, id);
return users;
}
}
public class UserRegisterAction extends ActionSupport implements ModelDriven {
UserRegister_VO userInfo = new UserRegister_VO();
private UserManager userManager;
public Object getModel() {
return userInfo;
}
public UserRegister_VO getUserInfo() {
return userInfo;
}
public void setUserInfo(UserRegister_VO userInfo) {
this.userInfo = userInfo;
}
public UserManager getUserManager() {
return userManager;
}
public void setUserManager(UserManager userManager) {
this.userManager = userManager;
}
}
------解决方案--------------------看你的使用的是注解注入吧?根本不需要实例化impl就可以得到了
------解决方案--------------------
Spring IOC,也就是控制反转,也就是说将对象以及依赖对象的实例化过程交给Spring IOC容器管理。不需要程序自身获取(也就是new一个对象)。也就是说,你UserManagerImpl中的UserDao是交给SpringIOC容器进行管理的。并不需要你手动new其中的依赖对象。因为这个过程完全由Spring IOC容器在你第一次getBean