我是 jsf 技术的新手,我试图了解ViewScoped jsf bean 的初始化时间和方式。
我有一个带有 2 个 bean 的示例应用程序
ApplicationScopedBean.java
@ManagedBean
@ApplicationScoped
public class ApplicationScopedBean implements Serializable {
private int incrementedCounter =0;
public int getIncrementedCounter() {
incrementedCounter += 1;
return incrementedCounter;
}
}
ViewScopedBean.java
@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 页面来显示这些值:
索引.xhtml
<?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 次?
提前致谢!
解决方案
正如评论中所述,原因是在我的 IntelliJ IDEA 的运行配置中选中了“启动浏览器”复选框。诀窍是当浏览器从 IDE 自动启动时,我已经将 viewScopedBean 初始化了 3 次。