gpt4 book ai didi

java - 多次构造 Eager ApplicationScoped 托管 beans

转载 作者:搜寻专家 更新时间:2023-11-01 00:51:40 26 4
gpt4 key购买 nike

我有一堆 eager ApplicationScoped 托管 bean。其中一些通过 ManagedProperty 注释注入(inject)到其他的中,形成一棵依赖树。每个依赖的 bean 在构建后操纵其父级。

但是,似乎每次注入(inject)都会创建一个新实例,从而使之前的操作无法完成。据我了解,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
}
}

最佳答案

我希望在 Tomcat 8 + Mojarra 2.2.0 上解决这个问题。在我的例子中,我只是从 web.xml 中删除了监听器声明

<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>

之后似乎调用了一次构造函数。

关于监听入口,有一部分BalusC answer of this问题。

In any case, the explicit registration of Mojarra's ConfigureListener in web.xml is actually only necessary to workaround old buggy servers such as GlassFish v3 and Jetty who failed to find the listener in Mojarra's TLD file. When deployed to a decent server, the whole entry is unnecessary.

关于java - 多次构造 Eager ApplicationScoped 托管 beans,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13007291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com