What does the @EJBs annotation do? What does the @EJBs annotation do? java java

What does the @EJBs annotation do?


The @EJB annotation (and @Resource, @WebServiceRef, etc.) serves two purposes:

  1. It declares a reference in the component namespace. For example, @EJB(name="myEJB") creates a reference java:comp/env/myEJB. If you annotate a field and do not specify a name, then it creates a reference java:comp/env/com.example.MyClass/myField.
  2. If the annotation is declared on a field or setter method, then the container performs injection when the component is created.

How the reference is resolved varies, independent of whether the reference is being resolved for a lookup("java:comp/env/myEJB") or due to injection:

  1. If EE 6+ is used, the lookup attribute requires a JNDI lookup to resolve the target.
  2. Some application servers support mappedName, which is specified to be vendor specific. This is usually implemented by performing a lookup.
  3. Application servers support bindings at deployment time. This is usually implemented by performing a lookup.
  4. If no other binding information is provided and the bean interface (beanInterface or the field type) is only implemented by a single EJB in the application, then the EJB specification requires that it fall back to that.
  5. If no other binding information is provided and #4 cannot work, some application servers will attempt to perform a lookup in the server namespace based on the ref name (for example, java:comp/env/myEJB might cause a lookup of myEJB in the server namespace).


Miljen Mikic's answer gave me an idea about the possible answer. If anyone who knows about JNDI reads this, please tell me if this is sane, as I'm basically guessing here.

Basically, there are 2 ways to look into the JNDI tree: either via a global path (/some/proprietary/path/my/bean) and via your program's environment (java:comp/env/my/bean). The idea is that you create references from the global path to you local environment, and then lookup the components from there.

So @Ejb(name="java:comp/env/my/bean",mappedName="/some/proprietary/path/my/bean") would create this reference from java code (without descriptor xml file).

This means @Ejb(name="java:comp/env/my/bean") is on its own a no-op: It copies a reference onto itself. It might hava as side effect the fact that you application server now knows at compile time that this reference is required,but that's about it.


According to this link, basically this annotation enables EJB to lookup external EJBs relatively to its context. Usually, there are more elegant ways to do that.