CDI Ambiguous dependency with @Produces - why?

前端 未结 3 1732
自闭症患者
自闭症患者 2020-12-06 11:13

I am using code like below:

public Configuration {

    private boolean isBatmanCar = someMethod(...);

    @Produces
    public Car getCar(@New Car car) {
          


        
3条回答
  •  情书的邮戳
    2020-12-06 11:38

    Using @Alternative works but should only be used if you want to be able to activate it through beans.xml.

    Suppressing the default constructor of your bean also works but you won't be able to use your bean in another scope than @RequestScoped.

    Using your own qualifier works but isn't very useful if you have only one implementation and just want to be able to instantiate your bean with a producer rather than with its constructor.

    The easiest way is to annotate your bean @Any :

    @Any
    public class Car {
    }
    ...
    @Produces
    public Car getCar() {
        return new Car();
    }
    ...
    @Inject
    Car car;
    

    Things that you have to keep in mind :

    • All beans and producers are always implicitly qualified @Any
    • Beans and producers without explicit qualifiers are implicitly qualified @Default
    • Beans and producers with explicit qualifiers are no longer implicitly qualified @Default
    • Injection points without explicit qualifiers are implicitly qualified @Default, but not @Any

    Regarding all this, the same code as above explicitly qualified looks like this :

    @Any
    public class Car {
    }
    ...
    @Produces
    @Any
    @Default
    public Car getCar() {
        return new Car();
    }
    ...
    @Inject
    @Default
    Car car;
    

    It becomes more obvious that the bean's default constructor isn't a valid possibility for the injection point and the producer is a valid possibility.

提交回复
热议问题