我的带有spring和hibernate的java项目,当我使用它时,无法获得sessionFactory.it的null。配置:
<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 :(得分:2)
您在main
方法中的测试并未实际使用Spring进行注射。您需要加载applicationContext.xml
,然后从中获取test
bean。
所以你可以在你的主要做这样的事情:
ApplicationContext context =
new ClassPathXmlApplicationContext(new String[] {"applicationContext.xml"});
Test test = (Test)context.getBean("test");
答案 1 :(得分:1)
您还需要从spring上下文中获取Test对象。加载config xml并创建上下文并从上下文中获取对象
例如
Test test = (Test) context.getBean("test");