在JSF托管bean中注入Spring托管的SessionFactory bean

时间:2015-05-06 20:23:55

标签: spring jsf-2 dependency-injection

如果我已经配置了如下的Spring + Hibernate,

<!-- 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"/>

如何将Spring会话工厂bean注入我的JSF托管bean?

1 个答案:

答案 0 :(得分:1)

只要您使用ContextLoaderListener初始化Spring上下文,就可以从JSF上下文中访问它。根据文件:

  

所有Java Web框架都构建在Servlet API之上,因此可以使用以下代码片段来访问ContextLoaderListener创建的“业务上下文”ApplicationContext。

WebApplicationContext ctx = WebApplicationContextUtils.
    getWebApplicationContext(servletContext);

Spring还有一个从JSF上下文中获取bean的隐式方法:

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

请记住,那种bean查找违反了DI规则。不要在你拥有的每一个bean中执行它,它会降低它们的可测试性。相反,使用@ApplicationScoped托管bean(您可以轻松地模拟单元测试)以返回Spring上下文。

另见:

相关问题