lovespring
lovespring

Reputation: 19569

How could this happen? about hibernate and spring and SessionFactory

I have a bean in spring's config, which is

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

and in my MVC controller, I use:

@autowired
SessionFactory sf;

and spring can inject hibernate's SessionFactory (not just the bean:LocalSessionFactoryBean)

how could this happen, SessionFactory is just a property of LocalSessionFactoryBean.

Upvotes: 0

Views: 80

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279960

You'll notice LocalSessionFactoryBean implements FactoryBean<SessionFactory>. This interface is used by Spring to create other types of beans. In this case a SessionFactory.

In simple terms, Spring will call getObject() on the instance of LocalSessionFactoryBean which will return the SessionFactory instance. To illustrate what goes on, take the Java config way of declaring beans.

@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();
}

You could also have returned a LocalSessionFactoryBean instance and Spring still would have called the getObject() method and populated its context with a SessionFactory instance.

There are tons of such FactoryBean implementations that are useful to Spring developers.

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691735

A FactoryBean is a factory for a given Spring bean type. When Spring injects a Foo, if it finds a bean of type FactoryBean<Foo> in its list of beans, then it will ask this factory to create a Foo, and inject this Foo. This allows delaying the bean creation until necessary, and customizing its creation (for example, when creating a bean is a complex process, or needs a custom scope).

Read the javadoc and the documentation for more details.

Upvotes: 2

Related Questions