【问题标题】:Reduce multiple calls to a greedy method减少对贪心方法的多次调用
【发布时间】:2023-03-13 20:14:01
【问题描述】:

我有以下 JSF 2.0 bean:

@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}

@SessionScoped
class MyPageBean {
  String userId;
  GreedyBean greedyBean;
  String getFirstGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getString();
  }
  int getSecondGreedyStuffStat() {
    Result result = greedyBean.doGreedyStuff(userId);
    return result.getInt();
  }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}

然后在我的 JSF 页面中:

<h:outputText value="#{myPageBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageBean.secondGreedyStuffStat}"/>

如何在不自己实现缓存机制的情况下将其重构为只调用一次GreedyBean::doGreedyStuff?如果 JSF 不能这样做,那么这样说是一个有效的答案。

注意事项:

  • 我对 JSF 几乎一无所知:我只修复了一个错误,然后我恢复了我通常的其他任务。
  • 我们使用 Spring 进行注入,我尝试在 JSF 注释中进行翻译。如果那里有错误,请原谅我。
  • 正如@JasperdeVries 所提到的,我不能在MyPageBean@PostConstruct 中拨打电话,因为数据不是最新的。结果应该在请求时是最新的,而不是在会话开始时。我理解这个原则并将执行它,尽管它在这种情况下对我没有帮助。

【问题讨论】:

  • @JasperdeVries 我猜一个显着的区别是提到了范围。我不能把它们放在我的会话 bean 的@PostConstruct 中,因为那会花费太多时间,而且如果会话持续时间过长,数据可能会过时......
  • 如果您需要将数据作为请求范围,为什么不将其移动到请求范围 bean?
  • @JasperdeVries 嗯...因为我不知道它存在(而且我正在修复的应用程序中似乎没有任何请求范围的 bean 作为示例)。谢谢你,我想我现在从更好的角度看待 JSF!
  • 没问题,很高兴我能帮上忙

标签: jsf jsf-2 scope


【解决方案1】:

根据@JasperdeVries'的解释,我需要添加一个新的request-scoped bean:

GreedyBean.java

@ApplicationScoped
class GreedyBean {
  Result doGreedyStuff(String userId) {
    ... // Takes lots of machine resources and time.
  }
}

MyPageBean.java(应该重命名为有关会话的内容,而不是页面)

@SessionScoped
class MyPageBean {
  String userId;
  String getUserId() { return userId; }
}

MyPageRequestBean.java

@RequestScoped
class MyPageRequestBean {
  // Beans
  MyPageBean myPageBean;
  GreedyBean greedyBean;

  // Data
  String firstGreedyStat;
  int secondGreedyStat;

  @PostConstruct
  public void init() {
    Result result = greedyBean.doGreedyStuff(myPageBean.getUserId());
    firstGreedyStat = result.getString();
    secondGreedyStat = result.getInt();
  }

  String getFirstGreedyStat() { return firstGreedyStat; }
  int getSecondGreedyStat() { return secondGreedyStat; }

  void setMyPageBean(MyPageBean myPageBean) { this.myPageBean = myPageBean; }
  void setGreedyBean(GreedyBean greedyBean) { this.greedyBean = greedyBean; }
}

myPage.xhtml

<h:outputText value="#{myPageRequestBean.firstGreedyStuffStat}"/>
<h:outputText value="#{myPageRequestBean.secondGreedyStuffStat}"/>

【讨论】:

    猜你喜欢
    • 2011-06-04
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2021-12-20
    • 2012-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多