你會注意到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開發人員非常有用。