我是jsf技术的新手,我正在尝试了解 ViewScoped jsf bean的初始化时间和方式。
我有一个带有2个豆子的示例应用程序
@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时,reincarnationNumber
都会增加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>
当我第一次启动应用程序时,我的reincarnationNumber
值已经等于 3 。
换句话说,我在浏览器中显示了这些信息:
ViewScoped bean reincarnation is 3
ViewScoped bean access counter is 1
为什么? 为什么ViewScoped bean创建了3次bean?
提前致谢!
正如评论中所述,原因是我的IntelliJ IDEA中的“运行配置”中选中了“启动浏览器”复选框。诀窍是当浏览器从IDE自动启动时,我将viewScopedBean初始化了3次。
答案 0 :(得分:0)
它没有被创建3次,只是多次调用getter ......那是因为......你可以查看这个答案: