Saptarsi
Saptarsi

Reputation: 888

Spring 5 + Hibernate 5 : How SessionFactory is getting Autowired with LocalSessionFactoryBean

I am developing REST apis using Spring MVC 5.0.8 and Hibernate 5.2.11

I have created AppConfig class,in which I have created getSessionFactory() method with return type LocalSessionFactoryBean

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();

        factoryBean.setDataSource(dataSource());
        factoryBean.setPackagesToScan("saptarsi.auditdb.model");
        factoryBean.setHibernateProperties(hibernateProperties());

        return factoryBean;
    }

And Inside DaoImpl class I have autowired SessionFactory

@Repository
public class LOcaldbDaoImpl implements LocaldbDao {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public void getAllApiDetails(HttpRequestEntity<ApiDetailsFilterDto> requestEntityDto) {
    }

}

And everything is working fine

But I want to know how SessionFactory is getting autowired.

Because I am not returning factoryBean.getObject(),which is responsible to return SessionFactory type object.

And @Autowire will look for SessionFactory type in Bean factory.

So how Autowiring is happening ?

Upvotes: 1

Views: 1071

Answers (2)

Oleg Spiridonov
Oleg Spiridonov

Reputation: 131

Because after you initialized the LocalSessionFactoryBean, the buildSessionFactory method was called. Link to calling.

protected SessionFactory buildSessionFactory(LocalSessionFactoryBuilder sfb) {
    return (this.bootstrapExecutor != null ? sfb.buildSessionFactory(this.bootstrapExecutor) :
            sfb.buildSessionFactory());
}

After that, SessionFactory bean will be in the ApplicationContext.

Upvotes: 4

Serhii Marynenko
Serhii Marynenko

Reputation: 56

All Spring beans was load in ApplicationContext. Try to read here more https://docs.spring.io/spring/docs/1.2.x/reference/beans.html

Upvotes: 2

Related Questions