EJB组件继承

时间:2016-03-18 11:30:50

标签: java-ee

我遇到了EJB组件继承问题。

我有以下组件。

@Remote
public interface A {

    void myMethod();
}

实现类如下:

@Stateless
public class AImpl implements A {

    @Override
    void myMethod(){}
}

来电者课程如下:

public class Caller {

    @EJB
    A bean;

    void someMethod{
        bean.myMethod();
    }
}

以上3个类是我们的框架类我不应该更改代码,我可以使用它们。在我的情况下,我通过扩展类AImpl来编写我的自定义类,并覆盖方法,如下所示。

@Remote(A.class)
@Stateless
class AImpl1 extends AImpl {

    @Override
    void myMethod(){}
} 

但是每当我的调用者每次执行bean.myMethod()时调用方法AImpl.myMethod(),我都想执行我的重写方法。有没有办法在运行时传递我的bean而不更改3个以上的类?

我知道如果我可以使用@EJB(name="AImpl1")更改Caller类,那么我的重写方法会执行但我无法执行此操作。

1 个答案:

答案 0 :(得分:0)

如果CDI托管bean解决方案是正确的。

1.,可配置的解决方案: 而不是派生使用A接口的多实现者,使用@Alternative注释标记它们+在beans.xml中注册适当的实现者。

@Alternative
@RequestScoped
public class AImpl1 implements A {...}

@Alternative
@RequestScoped
public class AImpl2 implements A {...}

public class Caller {
  @Inject
  private A bean;
  ...
}

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="annotated">

  <alternatives>
    <class>x.AImpl2</class>
  </alternatives>
</beans>

2.,运行时解决方案 使用@Producer + @Produces注释根据某些运行时状态创建实现者实例。 @Produces @AImplementor标记的方法在@Inject @AImplementor标记字段/ etc需要它们时创建实例。

public class AImplFactory {
  private static final int IMPL1 = 0;
  private static final int IMPL2 = 1;

  @Setter
  private AImplType aImplType = IMPL2;

  @Produces
  @AImplementor
  public A createAImplementor() {
    switch ( aImplType ) {
      case IMPL1: return new AImpl1();
      case IMPL2: return new AImpl2();
    }
  }
}

public class Caller {
  @Inject
  @AImplementor
  private A bean;
  ...
}
相关问题