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 Interface:
2: @EJB
EJB specific annotation, can use specific attributes like "beanName" and others:
EJB Interface
<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:
In the method above Crud is a generic business interface which is extended by our target EJB Remote and Home interfaces.