2014-10-22 63 views
5

由于sessionFactory对象始终为空,因此在UesrDAO类中获取空指针异常。如果这有帮助,我发现如果使用'new'手动创建DAO,而不是让spring处理它,会发生这种情况。我没有这样做,我在服务类中注入UserDAO,但仍然将sessionFactory设置为null。自动装配的sessionFactory对象为空

任何帮助表示赞赏,谢谢。

下面是相关文件的内容:

的hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> 

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="location"> 
      <value>/WEB-INF/properties/database.properties</value> 
     </property> 
    </bean> 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
     <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.hibernate4.LocalSessionFactoryBean"> 
     <property name="dataSource"> 
      <ref bean="dataSource"/> 
     </property> 
     <property name="hibernateProperties"> 
      <props> 
       <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 
       <prop key="hibernate.show_sql">true</prop> 
      </props> 
     </property> 
     <property name="packagesToScan"> 
      <list> 
       <value>org.questionbank.dto</value> 
      </list> 
     </property> 
    </bean> 
</beans> 

的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:security="http://www.springframework.org/schema/security" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
    http://www.springframework.org/schema/security 
    http://www.springframework.org/schema/security/spring-security-3.2.xsd 
    http://www.springframework.org/schema/context 
    http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/tx 
    http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd"> 

    <import resource="hibernate.cfg.xml"/> 
    <mvc:annotation-driven /> 
    <tx:annotation-driven /> 
    <context:annotation-config /> 
    <!-- To scan the components --> 
    <context:component-scan base-package="org.questionbank"/> 
    <bean id = "transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> 
     <property name = "sessionFactory" ref = "sessionFactory" /> 
    </bean> 
</beans>  

DAO类:

public class UserDAO 
{ 
    protected static Logger logger = Logger.getLogger("dao"); 

    @Autowired 
    private SessionFactory sessionFactory; 

    public UserDTO searchDatabase(String username) 
    { 
     logger.debug("Seraching for user in DB"); 
     UserDTO user=new UserDTO(); 
     Query query = sessionFactory.getCurrentSession().createQuery("FROM UserDTO u WHERE u.userName = :userName"); 
     query.setParameter("userName", username); 
     user = (UserDTO) query.uniqueResult(); 
     if(user!=null) 
      return user; 
     logger.error("User does not exist!"); 
     throw new RuntimeException("User does not exist!"); 
    } 
} 

服务类:

@Transactional(readOnly = true) 
public class CustomUserDetailsService implements UserDetailsService 
{ 
    protected static Logger logger = Logger.getLogger("service"); 
    @Autowired 
    private UserDAO userDAO; 
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException 
    { 
     UserDetails user = null; 
     try 
     { 
      UserDTO dbUser = userDAO.searchDatabase(username); 
      user = new User(
        dbUser.getUserName(), 
        dbUser.getPassword().toLowerCase(), 
        true, 
        true, 
        true, 
        true, 
        getAuthorities(Integer.parseInt(dbUser.getAccess()))); 
      } catch (Exception e) { 
      logger.error("Error in retrieving user"); 
      e.printStackTrace(); 
      throw new UsernameNotFoundException("Error in retrieving user"); 
     } 
     return user; 
    } 
+2

都成分标注有'@ Component'(或类似的注释,比如'@ Repository','@ Service'等)?另外,他们都是在'org.questionbank'还是一个子包? – 2014-10-22 01:08:31

+0

你可以发布堆栈跟踪吗? – 2014-10-22 01:09:52

+0

解决了,我没有在XML中使用UserDAO bean,也没有为它添加批注,添加批注的确有效。谢谢@AnthonyAccioly指出这一点。 – usercpd 2014-10-22 02:59:53

回答

2

您当前的配置,<context:annotation-config /><context:component-scan base-package="org.questionbank"/>允许的上半年在功能上,你为了让春节正确识别并注入你的bean需要。

另一半实际上是将bean声明为Spring管理的组件。

您可以通过两种方法之一来完成此操作。无论是宣布了<bean />标签(就像你与你的transactionManager所做的那样)在applicationContext.xml豆或使用stereotype annotation(如@Component@Repository@Service@Controller)。

@Repository 
public class UserDAO { // ... 

而且

@Service 
public class CustomUserDetailsService { // ... 
相关问题