提问者:小点点

jsf2 ViewScoped bean初始化


我是jsf技术的新手,我正在尝试了解ViewScoped jsf bean何时以及如何初始化。

我有一个包含2个bean的示例应用程序

@ManagedBean
@ApplicationScoped
public class ApplicationScopedBean implements Serializable {
    private int incrementedCounter =0;

    public int getIncrementedCounter() {
        incrementedCounter += 1;
        return incrementedCounter;
    }
}
@ManagedBean
@ViewScoped
public class ViewScopedBean implements Serializable {
    @ManagedProperty(value = "#{applicationScopedBean}")
    private ApplicationScopedBean applicationScopedBean;

    private int reincarnationNumber;

    private int accessCounter;

    @PostConstruct
    public void initialize() {
        accessCounter = 0;
        reincarnationNumber = applicationScopedBean.getIncrementedCounter();
        System.out.println("Initializing viewScoped stateManager with reincarnationNumber value = " + String.valueOf(reincarnationNumber));
    }

    public void noAction() {
        //do nothing
    }

    public int getReincarnationNumber() {
        return reincarnationNumber;
    }
    public int getAccessCounter() {
        accessCounter += 1;
        return accessCounter;
    }

    public ApplicationScopedBean getApplicationScopedBean() {
        return applicationScopedBean;
    }
    public void setApplicationScopedBean(ApplicationScopedBean applicationScopedBean) {
        this.applicationScopedBean = applicationScopedBean;
    }
}

ApplicationScoped bean只为应用程序启动创建一次。每次创建ViewScoped bean时,转世数都会增加1。

我还有一个简单的jsf页面来显示这些值:

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

<h:head>
    <title>View Scoped bean test</title>
</h:head>

<h:body>
    <h:form>    
        <p>ViewScoped bean reincarnation is <h:outputText value="#{viewScopedBean.reincarnationNumber}"/></p>
        <p>ViewScoped bean access counter is <h:outputText value="#{viewScopedBean.accessCounter}"/></p>

        <h:commandButton type="submit" value="no action" action="#{viewScopedBean.noAction()}"/>
        <h:commandButton type="submit" value="reload this page" action="index"/>
    </h:form>
</h:body>

</html>

当我第一次启动应用程序时,我已经有等于3的转世数值。

换句话说,我在浏览器中显示了这个信息:

ViewScoped bean reincarnation is 3
ViewScoped bean access counter is 1

为什么?为什么ViewScoped bean创建了3次bean?

提前感谢!

正如评论中所述,原因是在我的IntelliJ IDEA的运行配置中选中了“启动浏览器”复选框。诀窍是当浏览器从IDE自动启动时,我已经初始化了viewScopedBean 3次。


共1个答案

匿名用户

它没有创建3次,只是多次调用getter…那是因为…你可以检查这个答案:

为什么JSF多次调用getter