I have read many posts both online and SO, but I am still not clear on to which annotation to use for injecting an EJB.
Can anyone please guide when to use which annotation for injecting an EJB (and possibly pros and cons):
1) @EJB
2) @Resource
3) @Inject
This might be a basic question, I did look for answers, but I am not still clear on this.
I have never seen anywhere that you could use @Resource
for injecting an EJB. It might work in some servers but it is unlikely to be portable.
The question of @EJB
vs @Inject
is more complicated.
CDI and @Inject
were added to the Java EE 6 Specification. There it was possible to @Inject EJBs into a CDI bean, but not in too many other (if any) places.
The Java EE 7 Specification unified this substantially to the point where you can use @Inject
or @EJB
interchangeably in most (if not all) places. In essence all of the "sub" specifications such as the EJB spec itself, the servlet spec, JAX-WS, JAX-RS, etc had to be updated to support the use of @Inject
as well as @EJB
. However if you need to specify any of the attributes available on the @EJB annotation then these are not available on @Inject.
Therefore, feel free to use @Inject
anywhere if you're running in a Java EE 7 compliant environment and you don't have a need for any of the @EJB attributes, otherwise use @EJB
.