This question already has an answer here:
@ViewScoped calls @PostConstruct on every postback request

(1个答案)


4年前关闭。





我以为@ViewScoped应该可以防止在用户位于同一页面上时重新构造Bean。所以为什么我的@ViewScoped JSf控制器Bean甚至在动作处理程序导致浏览器导航之前就被创建了多次?从那个角度看?

有人可以在这里指出正确的方向吗?

这是我的代码:

视图(domain / edit.xhtml)

<h:form prependId="false">
    <h:inputText id="descriptionField" value="#{domainEdit.domain.description}" />
    <h:commandButton id="saveButton" value="save" action="#{domainEdit.save}" />
</h:form>


ViewScoped控制器(DomainEdit.java)

@Named("domainEdit")
@ViewScoped
public class DomainEdit implements Serializable {

    private static final long serialVersionUID = 1L;


    protected DomainEdit() {
    }

    @PostConstruct
    protected void init() {
        System.out.println("post construct called.");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("pre destroy called.");
    }

    public DomainEntity getDomain() {
        System.out.println("displaying domain...");

        // some code to return the domain
        return domain;
    }

    public String save() {
        System.out.println("saving...");

        // some saving code

        return "view";
    }
}


输出量

当我部署它并执行以下操作时,我得到以下输出:


导航到编辑视图(edit.xhtml)


   post construct called.
   displaying domain...
   pre destroy called.


更改domainDescriptionField输入文本的内容

没有记录
点击“保存”



  post construct called.
  displaying domain...
  pre destroy called.

  post construct called.
  displaying domain...
  pre destroy called.

  post construct called.
  displaying domain...
  pre destroy called.

  post construct called.
  displaying domain...
  pre destroy called.

  post construct called.
  displaying domain...
  saving domain...
  pre destroy called.

最佳答案

除非您使用的是JSF 2.2(目前尚不可用)或MyFaces CODI(我希望您会明确提到这一点),否则@ViewScoped在CDI中不起作用。这也几乎符合您的问题症状。

通过JSF而不是CDI管理bean。用@Named("domainEdit")包中的@ManagedBean替换javax.faces.bean。或者,安装MyFaces CODI以将JSF @ViewScoped桥接到CDI。

09-30 22:17