0

I have been studying @Produces annotation of CDI dependency injection from here. I just created my own same example. However, I am facing with ambiguous dependency.

public interface Bank {

    public void withdrawal();
    public void deposit();
}

public class BankOfAmerica implements Bank {

    @Override
    public void withdrawal() {
        System.out.println("Withdrawal from Bank of America");
    }

    @Override
    public void deposit() {
        System.out.println("Deposit to Bank of America");
    }
}

public class BankFactory {

    @Produces
    public Bank createBank() {
        return new BankOfAmerica();
    }
}

And this is the class which bean is get injected.

public class ProducesExample {

    @Inject
    private Bank bankOfAmerica;

    public void callBanksWithdrawal() {
        bankOfAmerica.withdrawal();
    }
}

I appreciate for any help.

EDIT: I know this a kind of duplicate of this question. However, in the tutorial which I shared, it says it should work. Moreover, there is only one type of bean so no need use @Default or @Alternatives but still get confused about why it is not working.

Community
  • 1
  • 1
quartaela
  • 2,579
  • 16
  • 63
  • 99

3 Answers3

1

The tutorial is a bit ambiguous (pun intended) about which classes should be deployed simulataneously in each step, so I wouldn't worry about that too much.

The answer to the other question you linked does match your case. BankOfAmerica is a bean of type Bank (in CDI 1.0 or in CDI 1.1+ with explicit beans), and your producer method is another bean of the same type, hence the ambiguous resolution.

Harald Wellmann
  • 12,615
  • 4
  • 41
  • 63
  • Thanks for your answer. I am just trying to understand. So in our context I have a "BankOfAmerica" bean and another bean called "ProducesExample" which has a producer method for Bank bean. I would expect when a Bank bean is going to get injected so that Producer method will be called and inject BankOfAmerica bean. Also, there is no other implementation for Bank interface. – quartaela Jan 28 '15 at 23:00
0

One thing that can be helpful is your beans.xml file.

If you want to have a factory (using @produces) you cannot have the bean-discovery-mode="all". If you have the all option than you will get Ambiguous dependencies exception cause all your implementations will be auto scanned as possible dependencies ( what in my opinion is a bad performance option ).

So put bean-discovery-mode="annotated" , leave your implementations cdi-annotation free and use @Dependent in the factory and @produces in the build method.

Gonçalo
  • 561
  • 5
  • 14
0

You have to add @BankProducer annotation like that :

public class BankFactory {

    @Produces
    @BankProducer
    public Bank createBank() {
        return new BankOfAmerica();
    } 

}

Busterleo
  • 1
  • 1