@Dependent范围在Wildfly中不是默认的吗? [英] Is @Dependent scope not default in Wildfly?

查看:992
本文介绍了@Dependent范围在Wildfly中不是默认的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Wildfly通过@Inject注入POJO时遇到了一些麻烦。文档明确指出:

I have some troubles with injecting POJOs via @Inject using Wildfly. The documentation clearly states:


@Dependent - 默认范围,如果没有指定;它意味着一个对象只存在一个客户端(bean)并且具有与该客户端(bean)相同的生命周期。

@Dependent - The default scope if none is specified; it means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).

但是,当我有两个班级时:

However, when I have two classes:

@Singleton
@Startup
public class A{
    @Inject
    private B b;
}

public class B{
    public B(){}
}

我一直在:


对于注入点有限定符@Default的类型B的不满意依赖性[ BackedAnnotatedField] @Inject [...]

Unsatisfied dependencies for type B with qualifiers @Default at injection point [BackedAnnotatedField] @Inject [...]

当我添加@Dependent时,一切都像魅力一样。我错过了什么吗?这种行为是野生蝇特有的吗?希望你能提供帮助,谢谢。

When I add @Dependent everything works like a charm. Am I missing something? Is this behavior wildfly-specific? Hope you can help, thanks.

推荐答案

在Java EE 7(CDI 1.1)中使用CDI时,默认的bean发现模式是注释。这意味着具有明确指定范围的任何bean都可用于注射。

When using CDI in Java EE 7 (CDI 1.1), the default bean discovery mode is annotated. Which means that any bean with an explicitly specified scope is available for injection.

因此,为了使您的bean B可用于注射,您可以:

So to make your bean B available for injection, you can either:


  1. 在B类上声明一个显式范围(这就是你在放置 @Dependent 时所做的事情)

  2. 声明 beans.xml 文件,并将 bean-discovery-mode 属性设置为所有。这将使您的存档中的所有bean都可用于注入(与Java EE 6(CDI 1.0)相同)。

  1. Declare an explicit scope on class B (that's what you are doing when putting @Dependent)
  2. Declare a beans.xml file with the bean-discovery-mode attribute set to all. This will make all beans of your archive available for injection (same behavior than Java EE 6 (CDI 1.0)).

beans.xml 文件必须位于 META-INF 文件夹中,如下所示:

The beans.xml file must be in the META-INF folder and looks like:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       version="1.1" 
       bean-discovery-mode="all">

</beans>

但是,我不建议使用 bean-discovery-mode =all

这篇关于@Dependent范围在Wildfly中不是默认的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆