I have found this question: What is the difference between @Inject and @EJB but I did not get any wiser. I have not done Java EE before nor do I have experience with dependency injection so I do not understand what I should use?
Is @EJB an old way of injecting? Is the injection done by the EJB container when using this annotation while using @Inject use the new CDI framework? Is that the difference and should I be using @Inject instead of @EJB if this is the case?
The @EJB
is used to inject EJB's only and is available for quite some time now. @Inject
can inject any managed bean and is a part of the new CDI specification (since Java EE 6).
In simple cases you can simply change @EJB
to @Inject
. In more advanced cases (e.g. when you heavily depend on @EJB
's attributes like beanName
, lookup
or beanInterface
) than in order to use @Inject
you would need to define a @Producer
field or method.
These resources might be helpful to understand the differences between @EJB
and @Produces
and how to get the best of them:
Antonio Goncalves' blog:
CDI Part I
CDI Part II
CDI Part III
JBoss Weld documentation:
CDI and the Java EE ecosystem
StackOverflow:
Inject @EJB bean based on conditions