问题描述
我有一堆渴望 ApplicationScoped
托管bean。其中一些是通过 ManagedProperty
注释注入其他注释,形成依赖树。每个依赖bean在构造之后操纵它的父级。
I have a bunch of eager ApplicationScoped
managed beans. Some of them are injected into others by the ManagedProperty
annotation, forming a tree of dependencies. Each depending bean manipulates its parent after construction.
然而,似乎为每次注入创建了一个新实例,从而使之前的操作被撤消。据我了解,只应创建一次 ApplicationScoped
bean。我误解了或者为什么会这样?是因为他们渴望?
However, it seems like a new instance is created for each injection, thus making previous manipulations undone. To my understanding, an ApplicationScoped
bean should only be created once. Have I misunderstood or why is this happening? Is it because they are eager?
这是一个例子:
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
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
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
}
}
推荐答案
我希望在Tomcat 8 + Mojarra 2.2.0上解决这个问题。
在我的情况下,我刚从web.xml中删除了监听器声明
I have hopefully resolved this problem on Tomcat 8 + Mojarra 2.2.0.In my case I just removed listener declaration from web.xml
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
之后似乎会调用构造函数。
Constructor seems to be called once afterwards.
关于听众的录入,有一部分BalusC回答了问题。
About listener entry, there is a part of BalusC answer of this question.
这篇关于渴望ApplicationScoped托管bean构建多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!