使用@Inject Instance 获取实现特定接口的 EJB 和 CDI bean

Using @Inject Instance to get EJB and CDI beans that implements specific interface

在我们的应用程序中,我们有结构如下的 CDI(@ApplicationScoped 注释)和 EJB(@Stateless 注释)bean:

MyInterface
    MyAbstractClass
       MyBean (CDI or EJB)

我在下面使用它来获取我的应用程序中实现 MyInterface:

的所有 bean(CDI 和 EJB)
@Inject
Instance<MyIterface> beans;

这里我看到两个奇怪的东西:

如何使用上面的注入获取所有 bean、CDI 和 EJB?

引自 EJB 3.2 规范第 4.9.2.1 节:

@Stateless
public class A implements Foo { ... }

@Stateless
public class B extends A implements Bar { ... }

Assuming Foo and Bar are local business interfaces and there is no associated deployment descriptor, session bean A exposes local business interface Foo and session bean B exposes local business interface Bar, but not Foo.

Session bean B would need to explicitly include Foo in its set of exposed views for that interface to apply. For example:

@Stateless
public class A implements Foo { ... }

@Stateless
public class B extends A implements Foo, Bar { ... }

在您的示例中,定义为 EJB 的 MyBean 不会公开 MyInterface,因此不会在 Instance<MyInterface> 处注入。

有两种处理方式:

  • 将 EJB 声明为实现 MyInterface
  • @Local(MyInterface.class)
  • 注释 EJB

关于 @Local 方法的警告 - 此 EJB 将仅满足那些使用作为注释参数提供的接口之一的注入点。您将无法在

时注入它
@Inject
MyBean bean;

此外,您将无法将注入的代理转换为任何其他类型。