【发布时间】:2018-01-13 14:37:09
【问题描述】:
我正在尝试通过 ServiceLocator 进行 EJB 查找,而无需硬编码 JNDI 名称,仅使用本地接口名称。问题在于 EJB 分布在其他模块 (JAR) 中。例如,我有这种情况:
项目-xxx:
@Stateless
class EjbXBean implements EjbX {
}
由容器向 JNDI 注册:java:global/project-xxx/EjbXBean
项目-yyy:
@Stateless
class EjbYBean implements EjbY {
}
由容器向JNDI注册:java:global/project-yyy/EjbYBean
EjbX 和 EjbY 都是@Local。我想让 EJB 只在另一个模块中执行此操作:
EjbX ejbx = ServiceLocator.lookup(EjbX.class);
EjbY ejby = ServiceLocator.lookup(EjbY.class);
但我不知道只有 ServiceLocator 内部的本地接口的模块(project-yyy 或 project-xxx)是什么。我不能只使用带有模块名称的整个 JNDI 名称进行查找:
EjbX ejbx = ServiceLocator.lookup("java:global/project-yyy/EjbXBean");
EjbY ejby = ServiceLocator.lookup("java:global/project-yyy/EjbYBean");
我试图弄清楚在这种情况下什么是最佳做法,因为我不知道硬编码的 JNDI 名称在 JavaEE 世界中是否是一种好的做法。
我使用 OpenEjb 4.7.4 进行开发和集成测试,使用 Wildfly 10.1.0 进行生产。
更新
我可以在 Wildfly 10.1.0 中使用 CDI:
@Override
public Object lookup(Class<?> type, Annotation... annotations) throws NamingException {
BeanManager manager = CDI.current().getBeanManager();
Iterator<Bean<?>> beans = manager.getBeans(type, annotations).iterator();
if (!beans.hasNext()) {
throw new NamingException("CDI BeanManager cannot find an instance of requested type " + type.getName());
}
Bean<?> bean = beans.next();
CreationalContext<?> ctx = manager.createCreationalContext(bean);
return manager.getReference(bean, type, ctx);
}
然后调用:
MyClass.lookup(EjbX.class);
但我不想使用 CDI,因为 I had some problems to put this to work 在可嵌入容器 (OpenEJB) 中。
【问题讨论】:
标签: jakarta-ee ejb jndi service-locator