2013-08-31 28 views
0

我在春天的配置,這是這怎麼會發生?關於Hibernate和Spring和SessionFactory的

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

,並在我的MVC控制器中的豆,我用:

@autowired 
SessionFactory sf; 

,春季可以注入Hibernate的SessionFactory的(不僅僅是bean:LocalSessionFactoryBean)

這怎麼會發生,SessionFactory只是LocalSessionFactoryBean的一個屬性。

回答

1

你會注意到LocalSessionFactoryBean implements FactoryBean<SessionFactory>。這個接口被Spring用來創建其他類型的bean。在這種情況下,SessionFactory

簡而言之,Spring將調用getObject()上的LocalSessionFactoryBean實例,它將返回SessionFactory實例。爲了說明發生了什麼,採用Java配置方式來聲明bean。

@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實例和春天還是會叫getObject()方法和填充它與一個SessionFactory實例上下文。

有許多這樣的FactoryBean實現對Spring開發人員非常有用。

2

FactoryBean是給定Spring bean類型的工廠。當Spring注入一個Foo時,如果它在其bean列表中發現了一個類型爲FactoryBean<Foo>的bean,那麼它會要求該工廠創建一個Foo,並注入Foo。這允許將bean的創建延遲到必要時,並定製其創建(例如,創建bean時是一個複雜的過程,或者需要定製範圍)。

閱讀the javadocthe documentation瞭解更多詳情。

相關問題