注入依赖bean

时间:2014-05-10 12:17:30

标签: java dependency-injection ejb ejb-3.0 cdi

我有一个班级

EntiyFacadeImpl.java

@Stateless
public class EntityFacadeImpl implements EntityFacade {

    @EJB
    ICustomerBean customerBean;

    public void printCustomer(Customer c) {
        customerBean.printCustomer(c);
        customerBean.additionalFieldsHandler(c.getAdditionalFields().toString());
    }

}

ICustomerBean 是@Local接口,有两个实现类 CustomerBean.java CustomerBeanExt.java ,后面的扩展 CustomerBean的.java

@Stateless(name = "CustomerBean")
public class CustomerBean implements ICustomerBean {

    public void printCustomer(Customer customer) {
        System.out.println(customer);
    }

    public void additionalFieldsHandler(String additionalFields) {
        // an empty implemetation here
    }
}

@Stateless(name = "CustomerExtBean")
public class CustomerExtBean extends CustomerBean implements ICustomerBean {

    @Override
    public void additionalFieldsHandler(String additionalFields) {
            // some custom implemetation
        System.out.println("Additional Fields: "+additionalFields);
    }
}

ICustomer 界面如下所示

@Local
public interface ICustomerBean {
    public void printCustomer(Customer c);
    public void additionalFieldsHandler(String additionalFields);
}

我的目标是每当我只在 SimpleRESTPojo.java 中注入 EntityFacade (EntityFacadeImpl的界面)时,我希望 CustomerExtBean 注入在其中,当任何其他类注入它时,我希望 CustomerBean 被注入

@Path("/pojo")
public class SimpleRESTPojo {

    @EJB
    private EntityFacade entityFacade;

}

我的应用的入口点仅限于EntityFacade。有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:0)

实际上,在看完你的问题后,看起来你正试图引入紧密耦合。 CDI并没有让EntityFacade知道注入的位置。我没有办法做到这一点。

您可以做的是创建使用此注入点的EntityFacade的扩展版本:

@Inject
@Extended //or whatever qualifier you come up with
private ICustomerBean  customerBean;

然后在扩展EntityFacade上使用相同的限定符。