依赖注入在EJB中如何遵循多态性工作。

huangapple go评论63阅读模式
英文:

How does dependency injection work in EJB's following polymorphism

问题

假设我有一个接口,我们称之为 A,并且有两个实现了这个接口的类。现在,当我进行依赖注入时,如何指定要调用哪个具体的实现。

@Local
interface SortAlgo{
   void sort();
}

class BubbleSort implements SortAlgo{
   void sort(){
     // 逻辑
   }
}

class InsertionSort implements SortAlgo{
   void sort(){
     // 逻辑
   }
}

现在是依赖注入的部分:

class SortArray{
  @EJB
  SortAlgo sortAlgo;
  System.out.println(sortAlgo.sort());
}

在这一点上,我将如何指定要选择哪个实现。

英文:

Suppose I have an interface, let's call it A and there are two classes that implement this interface. Now, when I'll be doing dependency injection, how do I mention which specific implementation to call.

@Local
interface SortAlgo{
   void sort();
}

class bubbleSort implements SortAlgo{
   void sort(){
     // logic
   }
}

class insertionSort implements SortAlgo{
   void sort(){
     // logic
   }
}

Now dependency injection

class SortArray{
  @EJB
  SortAlgo sortAlgo;
  System.out.println(sortAlgo.sort());
}

At this point how I'll mention which implementation to pick.

答案1

得分: 2

例如,如果您有通过Verizon或T-Mobile网关发送短信的SMS EJB,那么:

@Local
public interface SmsProvider { 
    public void sendSms(Sms sms);
}

T-Mobile:

@Stateless(name = "SmsProviderTMobile")
public class SmsProviderTMobile implements SmsProvider {
...
}

Verizon:

@Stateless(name = "SmsProviderVerizon")
public class SmsProviderVerizon implements SmsProvider {
...
}

然后您可以像这样注入特定的实现

```java
@EJB(beanName = "SmsProviderTMobile")
SmsProvider smsProviderTMobile;
英文:

For example, if you have SMS EJB which sends SMS via Verizon or T-Mobile Gateway, then:

@Local
public interface SmsProvider { 
    public void sendSms(Sms sms);
}

T-Mobile:

@Stateless(name = "SmsProviderTMobile")
public class SmsProviderTMobile implements SmsProvider {
...
}

Verizon:

@Stateless(name = "SmsProviderVerizon")
public class SmsProviderVerizon implements SmsProvider {
...
}

Then you can inject specific implementation like this:

@EJB(beanName = "SmsProviderTMobile")
SmsProvider smsProviderTMobile;

huangapple
  • 本文由 发表于 2020年10月25日 15:02:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64521175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定