【问题标题】:Why doesn't LocalSessionFactoryBean implement getCurrentSession, meanwhile the instance of SessionFactory can invoke the method?为什么LocalSessionFactoryBean不实现getCurrentSession,同时SessionFactory的实例可以调用该方法?
【发布时间】:2014-04-12 13:33:45
【问题描述】:

这是我对 Spring Bean 的配置:

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

然后我像这样在 DAO 层中使用它:

    @Resource(name = "sessionFactory")
    private SessionFactory sessionFactory;

我的问题终于来了:

    public T getById(int id) {
        Session session = sessionFactory.getCurrentSession();
    return (T) session.get(clz, id);
    }

总之,我的问题是:

"org.springframework.orm.hibernate4.LocalSessionFactoryBean"类中,没有SessionFactory's方法的实现——“getCurrentSessio”。

我跟踪LocalSessionFactoryBean's层次系统,但我没有找到方法“getCurrentSession”的实现。

期待您的回答,非常感谢!

【问题讨论】:

    标签: spring hibernate session code-injection


    【解决方案1】:

    一个工厂bean,顾名思义,就像一个工厂。它的作用是创建另一种类型的bean。 Spring 注入了这个工厂 bean 的产品,即工厂 bean 创建的对象。 LocalSessionFactoryBean 产生 SessionFactory

    欲了解更多信息,请阅读the documentation

    【讨论】:

    • 实现路线是这样的,但是这种方法的具体机制是什么?因为,通常情况下,我们直接将实例作为 bean 获取。还有一个问题:在 LocalSessionFactoryBean 中,SessionFactory 接口中没有 getCurrentSession 的实现。
    • 正如我所说,正如文档所说,当你声明一个作为 FactoryBean 实例的 bean 时,Spring 调用它的 getObject() 方法,并注入这个方法的结果而不是工厂 bean本身。 LocalSessionfactoryBean 的 getObject() 方法创建一个 SessionFactory,这个 Sessionfactory 是 Spring 注入的。
    • 知道了,那么我可以说几乎所有类名以“FactoryBean”结尾的类都必须实例化实例以通过相同的方法注入到Spring中。但是,正如我上面所说,方法“getCurrentSession”是在接口SessionFactory中声明的,工厂bean产生的实例如何提供接口方法的实现呢?谢谢!
    • 重要的不是类名以FactoryBean结尾。这只是 Spring 使用的命名约定。重要的是该类实现了FactoryBean 接口。
    • 是的,我知道。我只是谈谈约定。
    【解决方案2】:

    你看不到

    LocalSessionFactoryBean 的 getCurrentSession()

    它来自 api docs here

    受保护的抽象 SessionFactory buildSessionFactory() 抛出异常

    构建底层的 Hibernate SessionFactory。 回报: 原始的 SessionFactory(可能在暴露给应用程序之前用事务感知代理包装) 看看this

    默认情况下,这个工厂 bean 将公开一个事务感知的 SessionFactory 代理,让数据访问代码与普通的 Hibernate SessionFactory 及其 getCurrentSession() 方法一起工作,同时仍然能够参与当前 Spring 管理的事务:

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-01
      • 2014-03-20
      • 2012-10-23
      • 1970-01-01
      相关资源
      最近更新 更多