【问题标题】:can't get the sessionFactory无法获取 sessionFactory
【发布时间】:2012-05-07 07:18:00
【问题描述】:

我的带有 spring 和 hibernate 的 java 项目,无法获取 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);
}

【问题讨论】:

  • 您认为 sessionFactory 在哪里以及如何设置/初始化?不是,应该是。

标签: spring hibernate sessionfactory null-pointer


【解决方案1】:

您在main 方法中的测试实际上并未使用Spring 进行注入。您需要加载 applicationContext.xml 然后从中获取 test bean。

所以你可以在你的 main 中做这样的事情:

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

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

【讨论】:

    【解决方案2】:

    您还需要从 Spring 上下文中获取 Test 对象。加载您的配置 xml 并创建上下文并从上下文中获取对象

    例如。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-15
      • 2012-08-25
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 2017-10-23
      相关资源
      最近更新 更多