【问题标题】:Inject Spring managed SessionFactory bean in a JSF managed bean在 JSF 托管 bean 中注入 Spring 托管 SessionFactory bean
【发布时间】:2015-05-06 20:23:54
【问题描述】:

如果我配置了 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?

【问题讨论】:

    标签: spring jsf-2 dependency-injection


    【解决方案1】:

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

    所有 Java Web 框架都构建在 Servlet API 之上,因此可以使用以下代码 sn-p 访问由 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-lookup 是违反 DI 规则的。不要在你拥有的每一个 bean 中都执行它,它会降低它们的可测试性。相反,使用 @ApplicationScoped 托管 bean(您可以轻松地为您的单元测试模拟)以返回 Spring 上下文。

    另请参阅:

    【讨论】:

      猜你喜欢
      • 2013-01-23
      • 2012-01-27
      • 2015-03-11
      • 2014-07-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2013-07-28
      • 2013-05-08
      相关资源
      最近更新 更多