CHHIBI AMOR
CHHIBI AMOR

Reputation: 1265

EJB Dependency Injection with interface

I have an interface I with method m and two concrete implementations A and B.

public interface I{
   public void m();
}
public class A implements I{
  public void m(){
    //
   }
}
public class B implements I{
    public void m(){
     //
    }
}

I want to know when I inject I which of the two methods will be executed

@EJB
private I service;
///
service.m();
/////

Upvotes: 4

Views: 543

Answers (2)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

None of them, it will become into an error since the application server doesn't know which implementation to use. To avoid this, just provide the id of the class implementation, which by default is the same name of the class but starting with lower case:

//uncomment one of these
//@EJB(name="a")
//@EJB(name="b")
private I service;

Upvotes: 1

TheMP
TheMP

Reputation: 8427

None of them. The code will compile, but you won't be able to deploy it on your application server. Without specifing type of injected class, you will get an Exception similar to this:

org.jboss.weld.exceptions.DeploymentException:WELD-001409 Ambiguous dependencies
for type [...] with qualifiers [...] at injection point [...]. Possible dependencies
[...] with qualifiers [...], Managed Bean [...] with qualifiers [...]

Container (i.e. your application server) won't be able to recognize which field do you really want to inject (A or B). It cannot just guess it out of thin air. To avoid this kind of errors, provide it with annotation (called qualifier) specifying whether you want to inject class A or class B. If you want an example, you should see this article.

Upvotes: 0

Related Questions