简体   繁体   English

带接口的EJB依赖注入

[英]EJB Dependency Injection with interface

I have an interface I with method m and two concrete implementations A and B . 我有一个接口I与方法m和两个具体的实现AB

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 我想知道何时注入I将执行哪两种方法

@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: 为了避免这种情况,只需提供类实现的id,默认情况下该类的名称与类相同,但以小写字母开头:

//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). 容器(即您的应用程序服务器)将无法识别您确实要注入哪个字段(A或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 . 要避免这种错误,请为其提供注释(称为限定符),指定是否要注入A类或B类。如果您想要一个示例,您应该看到这篇文章

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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