It's not a secret anymore!*
The moose likes EJB Certification (SCBCD/OCPJBCD) and the fly likes @EJB annotation on field vs. class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » EJB Certification (SCBCD/OCPJBCD)
Bookmark "@EJB annotation on field vs. class" Watch "@EJB annotation on field vs. class" New topic

@EJB annotation on field vs. class

Ajay Dhar
Ranch Hand

Joined: Jan 26, 2011
Posts: 30
Can someone please explain to me the difference between annotating a field in an EJB with @EJB and annotating the EJB class with the @EJB annotation and how it relates to the ENC?

To my understanding, annotating a field with @EJB injects a reference to the EJB into the field. Does it look up in the ENC to do this injection? Is all injection done from the ENC?

What does annotating a bean class with @EJB do?

Some clarification on these topics would be greatly appreciated.


OCPJP 6, OCEEJBD 6, GIAC Secure Software Programmer-Java (GSSP-Java)
Prajakta Acharya
Ranch Hand

Joined: Nov 08, 2012
Posts: 138

Hi Ajay,

As you mentioned, annotating a field with @EJB injects EJB reference by looking up the JNDI name( specified by lookup property of @EJB)
@EJB on EJB class registers the EJB with a specific JNDI name (though it is registered by a default name in absence of 'name' property)

Ajay Dhar
Ranch Hand

Joined: Jan 26, 2011
Posts: 30
Thank you so much for your reply

So you are saying that using the @EJB annotation with the name property on the class registers that particular EJB in the ENC with the provided name. So, that means that the @EJBs annotation shouldn't be used at the class level because there is only one EJB that you can register, and that is the annotated EJB. Is this right? I'm not sure. Because it doesn't make sense to use the @EJBs annotation for a field because you can only inject one EJB into a given field. So when do you use the @EJBs annotation?
Ajay Dhar
Ranch Hand

Joined: Jan 26, 2011
Posts: 30
I did a little more reading and tinkering with code and I figured something out. Ok, the @Resource annotation applied to a field injects the resource into that field. The @Resource annotation applied to the class adds the particular resource specified in the annotation into the ENC for the annotated EJB. The EJB can then look up that resource using JNDI and a JNDI name of "java:/comp/env/...". Each EJB in an EJB jar has its own ENC and a WAR has one ENC for everything in the WAR.
It is sorta covered in the JavaRanch Style Guide.
subject: @EJB annotation on field vs. class
Similar Threads
jndi name in ejb3?
About ENC
Dependancy Injection when 2 Beans implement the same interface
Difference between @EJB and @Resource
The place where we define Annotations inside the EJB Bean class