日期:2014-05-18  浏览次数:20845 次

Spring整合Hibernate注入报空指针
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
       <context:annotation-config/>
       <context:component-scan base-package="com.jzh"/>

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
   <property name="driverClassName" value="${jdbc.driverClassName}"/>
   <property name="url" value="${jdbc.url}"/>
   <property name="username" value="${jdbc.username}"/>
   <property name="password" value="${jdbc.password}"/>
 </bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="mappingResources">
      <list>
        <value>com/jzh/model/User.hbm.xml</value>
      </list>
    </property>
    <property name="hibernateProperties">
      <props>
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
       <prop key="hibernate.show_sql">true</prop>
      </props>
    </property>
  </bean>



</beans>
**********************************************
package com.jzh.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.jzh.dao.UserDAO;
import com.jzh.model.User;


@Component("userManager")
public class UserManager {
private UserDAO userDAO;


public UserDAO getUserDAO() {//此处得不到userDAO

return userDAO;
}

@Resource(name="userDAO")
public void setUserDAO(UserDAO userDAO) {//但set可以得到
this.userDAO = userDAO;
}


public void saves(User user) 
{
  userDAO.save(user);//此处空指针

}

}
******************************************************************
package com.jzh.dao;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.stereotype.Component;

import com.jzh.model.User;