1

我在DAO中定義的會話工廠爲空。這裏是我的代碼:Spring嘗試將其注入到DAO中時Hibernate-sessionfactory爲空

@Repository 
public class LinkDetailsDAO { 

    private SessionFactory sessionFactory; 

    @Autowired 
    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 

    Session session = sessionFactory.getCurrentSession(); 

當我嘗試創建一個會話對象時拋出一個空指針。

我的applicationContext:

<!-- Load Hibernate related configuration --> 
    <import resource="hibernate-context.xml"/> 

<context:annotation-config/> 
<context:component-scan base-package="com.Neuverd.*"/> 

我休眠上下文:

<context:property-placeholder location="/WEB-INF/config/testapp.properties" /> 

<!-- Enable annotation style of managing transactions --> 
<tx:annotation-driven transaction-manager="transactionManager" /> 

<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions --> 
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 
p:dataSource-ref="dataSource" 
p:configLocation="/WEB-INF/config/hibernate.cfg.xml" 
p:packagesToScan="com.Neuverd"/> 

<!-- Declare a datasource that has pooling capabilities--> 
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 
destroy-method="close" 
p:driverClassName="${app.jdbc.driverClassName}" 
p:url="${app.jdbc.url}" 
p:username="${app.jdbc.username}" 
p:password="${app.jdbc.password}" 
/> 

和我的休眠配置文件

<hibernate-configuration> 
    <session-factory> 
     <!-- We're using MySQL database so the dialect needs to MySQL as well--> 
     <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> 
     <!-- Enable this to see the SQL statements in the logs--> 
     <property name="show_sql">true</property> 
     <property name="hbm2ddl.auto">create</property> 
    </session-factory> 
</hibernate-configuration> 

我有也嘗試使用@Resource註釋。但沒有運氣。我正在使用Spring 3.1和Hibernate 4.1。

由於上面提到的空指針引起的應用程序在啓動期間拋出了一個BeanDetailsDAO的beancreationexception。

在創建sessionfactory bean和transactionManager bean後,當容器嘗試創建LinkDetailsDAO bean時,它失敗。我不明白爲什麼會創建一個空的sessionfactory bean。試用了spring文檔中提到的sessionfactory。不工作。

+0

你檢查了春季啓動日誌嗎? – 2012-07-25 09:35:09

+0

爲什麼你不使用HibernateDaoSupport? – Saurabh 2012-07-25 09:39:16

+0

@kurt:是的。當通過ContextLoaderListener加載applicationContext時引發錯誤。 – shazinltc 2012-07-25 09:47:03

回答

2

您嘗試在構造函數中調用sessionFactory.getCurrentSession()。但是在Spring可以調用setter並注入會話工廠之前,必須首先構造對象。很顯然,在施工時,會話工廠爲空。

即使會話工廠在構造函數中注入,並且您之後要求會話,也不會有任何事務上下文,並且getCurrentSession()會引發異常。

您應該只從DAO的方法中獲得工廠的會話。這是獲取當前會話的方式,即與當前事務關聯的會話。

public void doSomething() { 
    Session session = sessionFactory.getCurrentSession(); 
    ... 
} 
+0

這很有道理,它也可以工作!非常感謝JB .. – shazinltc 2012-07-26 01:08:32

+0

我有疑問。當我說@Autowired \t private SessionFactory sessionFactory;是不是在構建DAO對象期間注入的bean(從我理解您在appcontext中定義的bean首先被創建)? – shazinltc 2012-07-26 01:12:27

+0

否。首先調用構造函數,然後通過反射填充該字段。 – 2012-07-26 05:54:43

相關問題