英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论