2012-04-26 204 views
0

我的java項目與春季和休眠,無法獲得sessionFactory.it的所有時間,當我使用它。配置:無法獲得sessionFactory

<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> 
    <property name="dataSource"> 
     <ref bean="dataSource" /> 
    </property> 
    <property name="hibernateProperties"> 
     <props> 
      <prop key="hibernate.dialect"> 
       org.hibernate.dialect.Oracle9Dialect 
      </prop> 
     </props> 
    </property> 
</bean> 

<bean id="test" class="test.Test"> 
    <property name="sessionFactory" ref="sessionFactory"></property> 
</bean>` 

Test.java的主要代碼是

 private SessionFactory sessionFactory; 

    public void setSessionFactory(SessionFactory sessionFactory) { 
     this.sessionFactory = sessionFactory; 
    } 
    public SessionFactory getSessionFacoty(){ 
     return this.sessionFactory; 
    } 
     public static void main(String[] args) { 
    // TODO Auto-generated method stub 
    Test test = new Test(); 
    System.out.println(test.sessionFactory); 
} 
+0

您認爲sessionFactory在哪裏以及如何設置/初始化?它不是,應該是。 – NimChimpsky 2012-04-26 14:26:02

回答

2

你在main方法實際上並沒有使用Spring注射試驗。您需要加載applicationContext.xml,然後從中獲取test bean。

所以你可以做這樣的事情在你的主:

ApplicationContext context = 
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"}); 

Test test = (Test)context.getBean("test"); 
+0

問題解決了,謝謝 – Dumlys 2012-04-26 14:58:13

1

你需要從Spring上下文測試對象爲好。加載你的配置xml並創建上下文,並從上下文中獲取對象。

Test test = (Test) context.getBean("test");