我可以在JavaEE 8中注入2个具有相同名称的接口吗?

时间:2017-11-16 10:40:37

标签: java java-ee jboss cdi

我的项目技术包是:JavaEE 8,Wildfly,Jboss 和这样的结构:

companycontext
  - company
  - workplace
  - employee
  - web (beans.xml here)

我在公司工作区项目中都有 EmployeeAdapter 界面。 因为CDI会发现每个项目中的每个bean,所以我会收到错误

A component named 'EmployeeAdapterImpl' is already defined in this module

目前我的解决方案名称如下: ComEmployeeAdapter WorkEmployeeAdapter ... 我可以使用 @Named

之类的内容
// Implement
@Stateless @Named("company")
EmployeeAdapterImpl implement EmployeeAdapter

// Using
@Inject @Named("company") private EmployeeAdapter

// Implement
@Stateless @Named("workplace")
EmployeeAdapterImpl implement EmployeeAdapter

// Using
@Inject @Named("workplace") private EmployeeAdapter

我认为命名我们的适配器比规则要好得多。

非常感谢。

1 个答案:

答案 0 :(得分:2)

这是一个EJB问题,而不是CDI问题。

CDI bean类型由完全限定的类名定义,因此在不同的包中有两个具有相同名称的bean没有问题。

由于您的两个EmployeeAdapterImpl bean是无状态会话bean,因此EJB容器将为它们生成JNDI名称。您可以在WildFly日志中看到它们,如

16:09:39.812 [MSC service thread 1-8] INFO  org.jboss.as.ejb3.deployment - WFLYEJB0473: JNDI bindings for session bean named 'Foo' in deployment unit 'deployment "myapp.war"' are as follows:

其中一个生成的名称的格式为

java:module/EmployeeAdapterImpl

只使用简单的类名,因此这会导致您的情况发生冲突。

您可能想要尝试name注释的mappedName@Stateless元素。