【问题标题】:How to Create Service class Object in Spring如何在 Spring 中创建服务类对象
【发布时间】:2014-05-17 13:54:26
【问题描述】:

我在我的项目中使用 ehcache,所以当服务器启动时,少数表的数据将被加载到缓存中。在我的应用程序中,我使用的是 Spring、Hibernate、JSF 我在 applicationCONtext.xml 文件中使用此配置

<bean id="cacheManager"  class="com.ccc.service.cache.CacheManager" init-method="init">
        <property name="delay" value="${timer.delay}" />
    </bean>   
 <bean id="companyCache" class="com.ccc.service.cache.clients.ValidCacheClient"/>

        <context:component-scan base-package="com.ccc.spring" />
        <context:annotation-config />
        <context:spring-configured />

在 Jsf Managed Bean 中,我正在创建这样的服务对象类

    @ManagedProperty(value = "#{GlobalDataService}")
    static GlobalDataService globalDataService;

但是在ValidCacheClient.java中如何创建Service类的对象呢? ValidCacheClient.java 不是托管类,那么如何创建 Object of Service 类?

【问题讨论】:

    标签: java spring jsf


    【解决方案1】:

    你有两个选择:

    • 注入必要的 bean 以从 JSF 获知为 ServletContext 属性,因此这些 bean 将被 JSF 视为应用程序范围的属性。您可以使用 Spring ServletContextAttributeExporter 来做到这一点:

      <bean class="org.springframework.web.context.support.ServletContextAttributeExporter">
          <property name="attributes">
              <map>
                  <entry key="globalDataService" value-ref="GlobalDataService" />
              </map>
          </property>
      </bean>
      

      那么你可以在JSF中毫无问题地注入它:

      @ManagedProperty(value = "#{globalDataService}")
      GlobalDataService globalDataService; //no need to be static
      
    • 让 Spring 容器管理 JSF 托管 bean 的生命周期。使用这种方法,您可以使用 @Autowired 注入 springs bean。这在 Spring 3 + JSF 2 教程中有所介绍。不过,请注意,如果您这样做,您将无法访问 JSF 2 视图范围(在同一视图中处理 ajax 请求时至关重要),因为Spring still cannot support it。但这可以通过为视图范围创建自定义实现来解决,例如Cagatay's

    IMO 我会使用后一种方法而不是前者。

    更多信息:

    【讨论】:

    • 我可以将服务类注入 JSFManagedBean 我想将它注入非托管 bean 类该怎么做?
    • @askkuber 阅读我发布的教程。网上也有很多关于它的教程。答案中的链接不是为了装饰目的,它们旨在为答案添加补充信息,而不是为了冗长的解释而重新发明轮子。
    • @askkuber 答案已更新。为第二种方法添加了更多相关信息。
    猜你喜欢
    • 1970-01-01
    • 2014-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 2019-05-03
    相关资源
    最近更新 更多