wwjdm
wwjdm

Reputation: 2596

Inject Spring managed SessionFactory bean in a JSF managed bean

If I have configured Spring+Hibernate as below,

<!-- Hibernate session factory -->
<bean id="sessionFactory"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
    <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL82Dialect</prop>
        <prop key="hibernate.show_sql">true</prop>
        <prop key="hibernate.format_sql">true</prop>
        <prop key="hibernate.current_session_context_class">thread</prop>
    </props>
</property>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>

<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="persistenceExceptionTranslationPostProcessor"
 class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

How do I inject the Spring session factory bean into my JSF managed bean?

Upvotes: 0

Views: 682

Answers (1)

Aritz
Aritz

Reputation: 31679

As long as you've initialized your Spring context using a ContextLoaderListener, you'll be able to access it from the JSF context. According to the docs:

All Java web frameworks are built on top of the Servlet API, and so one can use the following code snippet to get access to this 'business context' ApplicationContext created by the ContextLoaderListener.

WebApplicationContext ctx = WebApplicationContextUtils.
    getWebApplicationContext(servletContext);

Spring also has an implicit method to grab a bean from JSF context:

ApplicationContext ctx = FacesContextUtils
    .getWebApplicationContext(FacesContext.getCurrentInstance());
//Retrieve the bean by class or id
ctx.getBean("sessionFactory");

Remember that kind of bean-lookup is against the DI rules. Don't perform it in every single bean you have, it'll reduce their testability. Instead, use a @ApplicationScoped managed bean (which you can mock easily for your unit tests) in order to return the Spring context.

See also:

Upvotes: 1

Related Questions