多个ejb注射实现相同的接口

时间:2015-01-28 14:30:25

标签: dependency-injection ejb

我对这个ejb的东西很新。是否有可能在单个文件中我可以根据某些标准进行多次注射。

例如

public interface common(){
   public void sayhello();
    }

  beanA
     implements common()

  beanB
       implements common()

都是无状态豆

现在我有一个客户端需要根据某些条件触发hello方法。例如。如果字符串包含A,则根据控制台输入说,然后beanA应该注入beanB。 有可能吗?我的下一个问题是,我可以说这种动态注入不是由容器管理的吗?如果是这样我怎么能让容器控制?我需要一个示例代码或至少任何教程参考。

提前感谢!!

2 个答案:

答案 0 :(得分:0)

不,这不太可能。您可能能够使用线程本地或会话属性的自定义CDI范围,但我不推荐它。相反,只需注入对两个EJB的引用,并根据需要选择要使用的引用:

@EJB(beanName="BeanA")
Common beanA;
@EJB(beanName="BeanB")
Common beanB;

private Common getCommon(String input) {
    return isBeanAInput(input) ? beanA : beanB;
}

答案 1 :(得分:-1)

你可以这样做:

public interfaces ICommon {
    public void sayhello();
}

@Stateless
@LocalHome
public class BeanA implements ICommon {

    public void sayhello() {
        // say hallo 
    }

}

@Stateless
@LocalHome
public class BeanB implements ICommon {

    public void sayhello() {
        // say hallo 
    }

}

这里是使用EJB服务的CDI“客户端”

@Model
public void MyJSFControllerBean {

    @Inject
    private BeanA beanA;

    @Inject
    private BeanB beanB;

    public String sayhello(final String input) {
        if("a".equals(input)) {
            beanA.sayhello();
        } else {
            beanB.sayhello();
        }

        return "success";
    }

}

或者另一种解决方案是创建一个CDI生成器来创建它。但后来你混合了两个不同的概念。但我认为这取决于你的具体用例。

动态注射不存在!使用@Produce和@Qualifier,您可以控制要注入的所需CDI bean的创建。但这仅适用于CDI而不适用于EJB。

这里是CDI制作人的例子:

public void ICommonProducer {

    @EJB
    private BeanA beanA;

    @EJB
    private BeanB beanB;

    @Produces
    public ICommon produce() {
        final String input = "?????";
        // but here you have the problem that must get the input from elsewhere....

        if("a".equals(input)) {
            beanA.sayhello();
        } else {
            beanB.sayhello();
        }
    }

}

@Model
public void MyJSFControllerBean {

    @Inject
    private ICommon common;

    public String sayhello(final String input) {
        common.sayhello();
        return "success";
    }

}

我没有看过这段代码......