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
@EJBis used to inject EJB’s only and is available for quite some time now.@Injectcan inject any managed bean and is a part of the new CDI specification (since Java EE 6).In simple cases you can simply change
@EJBto@Inject. In more advanced cases (e.g. when you heavily depend on@EJB‘s attributes likebeanName,lookuporbeanInterface) than in order to use@Injectyou would need to define a@Producerfield or method.These resources might be helpful to understand the differences between
@EJBand@Producesand 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