CDI对@Produces的不明确依赖 - 为什么? [英] CDI Ambiguous dependency with @Produces - why?
问题描述
我使用的代码如下:
public Configuration {
private boolean isBatmanCar = someMethod(...);
@Produces
public Car getCar(@New Car car) {
if(isBatmanCar) {
car.setName("BatmanCar");
}
return car;
}
}
public Car {
private String name = "NormalCar";
public void setName(String name) {
this.name = name;
}
}
public Demo {
@Inject
Car car;
// rest of code
}
部署时glassfish的应用程序(Java EE 6顺便说一句)我得到了
When I deploy an application to glassfish (Java EE 6 btw) I get
AmbiguousResolutionException:WELD-001318无法解决(...)Car之间的模糊依赖关系与限定符[@Any @Default](...)制作方法[Car]与限定符[@Any @Default]
我知道当我将 @Alternative
添加到Car类时,它会起作用,但我想知道这是否是正确的方法,为什么我必须这样做?
I know that when I add @Alternative
to Car class it will work, but I wonder if this is the proper way to do it, and why do I have to do it?
在这种情况下你能告诉我@Produces的正确用法是什么吗?
Can you tell me what is the correct usage of @Produces in such case?
我正在使用Java EE 6,CDI 1.0,EJB 3.1,Glassfish 3.2
I'm using Java EE 6, CDI 1.0, EJB 3.1, Glassfish 3.2
推荐答案
错误来自于你有2个类型为
The error comes from the fact that you have 2 beans of type Car
, one being the class, the other being the producer. You have 2 obvious solutions to resolve the ambiguity:
首先,你把逻辑放在原来的 isBatmanCar
字段中class(在构造函数或 @PostConstruct
方法中)并删除您的生产者。那只会留下一个 Car
bean。
First, you put the logic behind isBatmanCar
field in the original class (in a constructor or a @PostConstruct
method for instance) and remove your producer. That would left only one Car
bean.
或者如果你真的想拥有2个bean或者无法避免你应该为你的生产bean创建一个限定符:
Or if you really want to have 2 bean or can't avoid it you should create a qualifier for your produced bean:
@Target({ TYPE, METHOD, PARAMETER, FIELD })
@Retention(RUNTIME)
@Documented
@Qualifier
public @interface BatmanChecked {
}
并在生产者处使用它,
@Produces
@BatmanChecked
public Car getCar(Car car) {...}
能够注入汽车的类型
@Inject
Car stdCar;
@Inject
@BatmanChecked
Car batCheckedCar;
限定符是解决模糊注入的自然选择。使用 @Alternative
也可以,但这不是一个好习惯。
Qualifier is the natural option to resolve ambiguous injection. Using @Alternative
also works but it's more a trick here than a good practice.
最后评论:<$ c这里不需要$ c> @New ,因为你的 Car
bean没有范围(所以 @Dependent
作用域)。 @New仅在生产者注入一个范围不是 @Dependent
的bean时才有用。也就是说,如果 Car
类在范围 @Dependent
中,则此代码不是很有用。
Last remark: @New
is not necessary here, since your Car
bean has no scope (so is @Dependent
scoped). @New is only useful when a producer inject a bean with a scope that is not @Dependent
. That said, this code is not very useful if your Car
class is in scope @Dependent
.
这篇关于CDI对@Produces的不明确依赖 - 为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!