简体   繁体   中英

How does dependency injection work in EJB's following polymorphism

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.

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;

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