在每个视图上调用会话范围的 bean 方法

Call session scoped bean method on every view

也许这是一个我应该能够找到文档的问题,但我不熟悉很多行话,所以我很挣扎。

基本上,我使用的是 JSF2。我有一个 SessionScoped bean,它使用 postconstruct init() 方法。我希望每次会话开始时都调用 init() 方法,这工作正常,但我也希望每次加载视图时调用它。

有没有简单的方法来做到这一点?

谢谢!

@PostConstruct 替换为 <f:event type="preRenderView">

<f:event type="preRenderView" listener="#{sessionScopedBean.init}" />

然而,更好的方法是将它分成 2 个豆子:一个 @SessionScoped 一个和一个 @ViewScoped 一个。然后只需在视图中引用 @ViewScoped 并将 @SessionScoped 作为 @ViewScoped 的 属性 注入。

@Named
@ViewScoped
public class ViewScopedBean {

    @Inject
    private SessionScopedBean sessionScopedBean;

    @PostConstruct
    public void init() {
        // ...
    }

    // ...
}

另请参阅:

  • When to use f:viewAction / preRenderView versus PostConstruct?
  • How to choose the right bean scope?