需要注射@Qualifier

jFr*_*tic 2 java-ee cdi

是否需要@Qualifier注释?我们不能只注入特定类型的实例吗?这似乎是一些额外的工作,因为我们必须为每个实现类创建注释类型.为了表明我的意思,以下是以下示例:

@Documented
@Retention(RUNTIME)
@Qualifier
public @interface AppleQ { }

@Documented
@Retention(RUNTIME)
@Qualifier
public @interface CheeseQ { }

public interface Eatable { }

@AppleQ
public class Apple implements Eatable { }

@CheeseQ
public class Cheese implements Eatable { }

public class Breakfast {
  @Inject @AppleQ Eatable somethingToEat;
}
Run Code Online (Sandbox Code Playgroud)

VS

public interface Eatable { }

public class Apple implements Eatable { }

public class Cheese implements Eatable { }

public class Breakfast {
  @Inject Apple somethingToEat;
}
Run Code Online (Sandbox Code Playgroud)

jan*_*oth 7

你是(好的),你的例子没有限定词.但更确切地说,你的例子比你不需要限定符有点误导.

通常,只要有多个特定类型的托管bean符合注入要求,就需要限定符.在您的示例中不是这种情况,但如果您编写如下代码很容易:

public class Breakfast {
  @Inject Eatable somethingToEat;
}
Run Code Online (Sandbox Code Playgroud)

(这使您可以灵活地在以后更改实现,原因与您通常编写的相同List list = new ArrayList())

你会不会,如果你只有一个管理某一类资格注射的豆需要预选赛.

想要使用限定符的更严重的示例如下所示:

想象一下,你想要Locale在你的系统中有一个类.使用不同的限定符(以及不同的生成器方法)将允许您编写如下代码:

...
@Inject
@DefaultLocale
Locale theDefaultLocale;
...
@Inject
@StandardLocale
Locale theStandardLocale;
...
@Inject 
Instance<Locale> allLocales;
...
Run Code Online (Sandbox Code Playgroud)

总结一下:当且仅当您有多个类型的bean时,才需要限定符.这使得限定符对于绝大多数的bean来说都是多余的 - 但你肯定需要它们.

所有这些以及更多内容最好在这里阅读.