【发布时间】: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!
-
没问题,很高兴我能帮上忙