title: Lookup an EJB by local interface in a multi module project
body: <p>I'm trying to made EJB lookups by ServiceLocator without hardcoded the JNDI name, using  only the local interface name. The problem is that the EJBs are distributed in other modules (JARs). Per example, I have this scenario:</p>
  
  <p><strong>project-xxx</strong>:</p>
  
  <pre><code>@Stateless
  class EjbXBean implements EjbX {
  
  }
  </code></pre>
  
  <p>Registered by the container with the JNDI: <code>java:global/project-xxx/EjbXBean</code> </p>
  
  <p><strong>project-yyy</strong>:</p>
  
  <pre><code>@Stateless
  class EjbYBean implements EjbY {
  
  }
  </code></pre>
  
  <p>Registered by the container with the JNDI: <code>java:global/project-yyy/EjbYBean</code> </p>
  
  <p>EjbX and EjbY are both <code>@Local</code>. I would like to get the EJB only doing this in another module:</p>
  
  <pre><code>EjbX ejbx = ServiceLocator.lookup(EjbX.class);
  EjbY ejby = ServiceLocator.lookup(EjbY.class);
  </code></pre>
  
  <p>But I don't know what is the module (project-yyy or project-xxx) only with the local interface inside the ServiceLocator. I can't only do the lookup using the entire JNDI name with the module name: </p>
  
  <pre><code>EjbX ejbx = ServiceLocator.lookup("java:global/project-yyy/EjbXBean");
  EjbY ejby = ServiceLocator.lookup("java:global/project-yyy/EjbYBean");
  </code></pre>
  
  <p>I'm trying to figure out what is the best practice in this case, because I don't know if the hardcoded the JNDI name is a good practice or not in the JavaEE world. </p>
  
  <p>I'm using OpenEjb 4.7.4 for development and integration tests, Wildfly 10.1.0 for production.</p>
  
  <h1>Update</h1>
  
  <p>I can to this using CDI in Wildfly 10.1.0:</p>
  
  <pre><code>@Override
  public Object lookup(Class&lt;?&gt; type, Annotation... annotations) throws NamingException {
      BeanManager manager = CDI.current().getBeanManager();
      Iterator&lt;Bean&lt;?&gt;&gt; beans = manager.getBeans(type, annotations).iterator();
  
      if (!beans.hasNext()) {
          throw new NamingException("CDI BeanManager cannot find an instance of requested type " + type.getName());
      }
      Bean&lt;?&gt; bean = beans.next();
      CreationalContext&lt;?&gt; ctx = manager.createCreationalContext(bean);
      return manager.getReference(bean, type, ctx);
  }
  </code></pre>
  
  <p>And to call:</p>
  
  <pre><code>MyClass.lookup(EjbX.class);
  </code></pre>
  
  <p>But I would not like to use CDI because <a href="https://stackoverflow.com/questions/45538143/problems-with-cdi-in-setup-for-functional-testing-with-tomee-or-openejb-jetty">I had some problems to put this to work</a> in an embeddable container (OpenEJB).</p>