我一直在尝试学习使用 Spring 3.0.x 的各种功能,当我尝试将 session 工厂注入(inject) DAO 实现时遇到了一个问题。当我尝试使用注入(inject)的 SessionFactory 实例变量时,我收到 NullPointerException,这使我相信问题存在于 bean 定义中。
dispatcher-servlet.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"
xmlns:p="http://www.springframework.org/schema/p"
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-2.5.xsd">
<context:component-scan base-package="com.timerecorder"/>
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@xxx.xxx.x.xxx:xxxx:xx"/>
<property name="username" value="xxx"/>
<property name="password" value="xxx"/>
</bean>
<bean id="mySessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
</value>
</property>
</bean>
</beans>
EntryImpl.java
package com.timerecorder.entity;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class EntryImpl implements EntryDao
{
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
@Override
public boolean saveEntry(EntryForm efd)
{
// Place the details from the entry form into the Entry entity
Entry e = new Entry();
e.setId(Long.valueOf(efd.getUserId()));
this.sessionFactory.getCurrentSession().save(e);
return true;
}
@Override
public boolean removeEntry(Long id)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List getEntries(Long id)
{
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Entry getEntry(Long id)
{
return new Entry();
}
}
如有任何帮助,我们将不胜感激。
亲切的问候,
贾斯汀
最佳答案
看起来这可能是您的 bean 定义中的命名约定问题。
尝试重命名
id=“mySessionFactory”
至
id= "sessionFactory"
请告诉我这是否有帮助。
关于java - Spring SessionFactory 注入(inject)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6565243/