简体   繁体   中英

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();
/////

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;

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 (ie 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM