我有一堆急切 ApplicationScoped
的托管豆子。其中一些通过ManagedProperty
注解注入到另一些中,形成依赖树。每个依赖 bean 在构造后都会操作其父级。
但是,似乎每次注入都会创建一个新实例,从而撤消先前的操作。据我了解,一个ApplicationScoped
bean 应该只创建一次。我是否误解或为什么会发生这种情况?是因为他们渴望吗?
这是一个例子:
ParentBean.java
package example;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
@ManagedBean(eager = true)
@ApplicationScoped
public class ParentBean
{
static int initCount = 0;
// ...
@PostConstruct
public void init()
{
++initCount; // Will end up being between 1 and 3. Expected always 1.
// ...
}
}
Child1Bean.java
package example;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
@ManagedBean(eager = true)
@ApplicationScoped
public class Child1Bean
{
@ManagedProperty("#{parentBean}") ParentBean parentBean;
public ParentBean getParentBean()
{
return parentBean;
}
public void setParentBean(ParentBean parentBean)
{
this.parentBean = parentBean;
}
@PostConstruct
public void init()
{
// manipulate parentBean
}
}
Child2Bean.java
package example;
import javax.annotation.PostConstruct;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
@ManagedBean(eager = true)
@ApplicationScoped
public class Child2Bean
{
@ManagedProperty("#{parentBean}") ParentBean parentBean;
public ParentBean getParentBean()
{
return parentBean;
}
public void setParentBean(ParentBean parentBean)
{
this.parentBean = parentBean;
}
@PostConstruct
public void init()
{
// manipulate parentBean
}
}