Reputation: 2757
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.
Upvotes: 0
Views: 1091
Reputation: 1
You have to add @BankProducer annotation like that :
public class BankFactory {
@Produces
@BankProducer
public Bank createBank() {
return new BankOfAmerica();
}
}
Upvotes: 0
Reputation: 630
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.
Upvotes: 0
Reputation: 12855
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.
Upvotes: 1