我在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。不工作。
你檢查了春季啓動日誌嗎? – 2012-07-25 09:35:09
爲什麼你不使用HibernateDaoSupport? – Saurabh 2012-07-25 09:39:16
@kurt:是的。當通過ContextLoaderListener加載applicationContext時引發錯誤。 – shazinltc 2012-07-25 09:47:03