0

我在spring的配置中有一个bean,它是

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

在我的 MVC 控制器中,我使用:

@autowired
SessionFactory sf;

而spring可以注入hibernate的SessionFactory(不仅仅是bean:LocalSessionFactoryBean)

怎么会这样,SessionFactory 只是LocalSessionFactoryBean.

4

2 回答 2

2

FactoryBean 是给定 Spring bean 类型的工厂。当 Spring 注入 aFoo时,如果它FactoryBean<Foo>在它的 bean 列表中找到一个类型的 bean,那么它会要求这个工厂创建 a Foo,并注入 this Foo。这允许将 bean 创建延迟到必要时,并自定义其创建(例如,当创建 bean 是一个复杂的过程,或者需要自定义范围时)。

阅读javadoc文档以获取更多详细信息。

于 2013-08-31T16:00:23.107 回答
1

你会注意到LocalSessionFactoryBeanimplements FactoryBean<SessionFactory>。这个接口被 Spring 用来创建其他类型的 bean。在这种情况下,一个SessionFactory.

简单来说,Spring 会调用将返回该getObject()实例的实例。为了说明发生了什么,请采用 Java config 声明 bean 的方式。LocalSessionFactoryBeanSessionFactory

@Bean 
public SessionFactory sessionFactory() throws IOException {
    LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
    sessionFactoryBean.setDataSource(dataSource());
    Properties hibernateProperties = new Properties();
    sessionFactoryBean.setHibernateProperties(hibernateProperties);
    sessionFactoryBean.afterPropertiesSet();

    return sessionFactoryBean.getObject();
}

您也可以返回一个LocalSessionFactoryBean实例,而 Spring 仍然会调用该getObject()方法并使用实例填充其上下文SessionFactory

有很多这样的FactoryBean实现对 Spring 开发人员很有用。

于 2013-08-31T16:00:15.520 回答