简体   繁体   中英

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM