@Inject vs @EJB and Direct JNDI Lookup

01 April 2014

Three different ways to get an EJB reference in Java

1: @Inject

Preferrable way as for JavaEE6 and beyond, CDI api gives greater flexibility for your java classes and it's nowadays considered the standard way of integrating managed lifecycle components in the JavaEE platform.

@Inject
private UserServiceBeanLocal userService;

Inject Interface:

@Target(value = {ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface Inject {
}



2: @EJB

EJB specific annotation, can use specific attributes like "beanName" and others:

@EJB(mappedName = "ejb/UserService")
private UserServiceBeanLocal userService;

EJB Interface

@Target(value = {ElementType.TYPE, ElementType.METHOD, ElementType.FIELD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface EJB {

<span class="kd">public</span> <span class="n">String</span> <span class="nf">name</span><span class="o">()</span> <span class="k">default</span> <span class="s">""</span><span class="o">;</span>

<span class="kd">public</span> <span class="n">String</span> <span class="nf">beanName</span><span class="o">()</span> <span class="k">default</span> <span class="s">""</span><span class="o">;</span>

<span class="kd">public</span> <span class="n">Class</span> <span class="nf">beanInterface</span><span class="o">()</span> <span class="k">default</span> <span class="n">Object</span><span class="o">.</span><span class="na">class</span><span class="o">;</span>

<span class="kd">public</span> <span class="n">String</span> <span class="nf">mappedName</span><span class="o">()</span> <span class="k">default</span> <span class="s">""</span><span class="o">;</span>

}



3: JNDI Lookup

In simple Java POJOs or classes that doesn't have support for injection dependency mechanisms, you can realize a direct JNDI Lookup to get and EJB instance. In this example a simple Hashmap based cache is added to enhance performance for repeated lookups:

/
Read from Local Home Interface if EJB container is located in same JVM, otherwise use
remote interface
/
   public Crud getLocalHome(String jndiHomeName) throws ServiceLocatorException {
     Crud home = null;
     try {
       if (cache.containsKey(jndiHomeName)) {
           home = (Crud) cache.get(jndiHomeName);
       } else {
           home = (Crud) ic.lookup(jndiHomeName);
           cache.put(jndiHomeName, home);
       }
      } catch (NamingException ne) {
           throw new ServiceLocatorException(ne);
      } catch (Exception e) {
           throw new ServiceLocatorException(e);
      }
      return home;
   }

In the method above Crud is a generic business interface which is extended by our target EJB Remote and Home interfaces.

comments powered by Disqus