通过Producer类将RequestScoped CDI Bean注入ApplicationScoped CDI Bean [英] Injecting RequestScoped CDI Bean into ApplicationScoped CDI Bean via Producer class
问题描述
本文解释了您可以将RequestScoped bean注入ApplicationScoped bean,并且客户端代理将在请求期间指向正确的实例:
在CDI中更大范围的bean实例中注入更短范围的Bean实例 - 它是如何工作的?
This article explains that you can inject RequestScoped beans into ApplicationScoped beans and the client proxy will point to the correct instance during a request: Bean instance of a shorter scope injected in a bean instance of a larger scope in CDI - how does it work?
当使用一个单独的生成器类来执行一些额外的处理并生成RequestScoped bean时,这是如何工作的?
部署到应用程序服务器后,由于受管理的bean和我的生成器方法都符合条件,因此由于模糊的依赖关系而得到DeploymentException。
How does this work when using a separate producer class that does some extra processing and produces the RequestScoped bean? Upon deployment to the application server I get a DeploymentException due to ambiguous dependencies since both the managed bean and my producer method are eligible.
推荐答案
确实,它有效。在这种情况下,CDI impl只在需要时执行你的 @Produces
方法。
Indeed, it works. In such case CDI impl just executes your @Produces
method whenever needed.
你得到了你的例外,因为CDI搜索了bean按类型和你有两个相同类型的定义。因此,如果您已经使用 @Produces
声明了bean,则不能让CDI在类路径上具有完全相同的bean定义。
You got your exception because CDI searches for beans by type and your have two definitions of the same type. So if you have declared already bean with @Produces
you cannot let CDI to have exactly the same bean definition available on the classpath.
以下示例无效:
@ApplicationScoped
public class SomeFactory {
@Produces
public SomeBean produceSome() {
return new SomeBean();
}
}
@RequestScoped // bug, redundant definition
public class SomeBean {
}
Ps。详细信息还取决于 bean-discovery-mode
的实际值。
Ps. Details also depend on the actual value of the bean-discovery-mode
.
您还可以查看此示例 SO回答。
就我个人而言,我不是粉丝自动发现和类路径扫描 - 但这个概念是CDI和Java EE的基础。这是我通常不推荐人Java EE服务器的原因之一。
Personally, I'm not a fan of auto-discovery and classpath scanning - but this concept lies at the foundation of the CDI and Java EE. That's one of the reasons I usually don't recommend people Java EE servers.
这篇关于通过Producer类将RequestScoped CDI Bean注入ApplicationScoped CDI Bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!