Should I use @EJB or @Inject
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
Update: This answer may be incorrect or out of date. Please see comments for details.
I switched from @Inject
to @EJB
because @EJB
allows circular injection whereas @Inject
pukes on it.
Details: I needed @PostConstruct
to call an @Asynchronous
method but it would do so synchronously. The only way to make the asynchronous call was to have the original call a method of another bean and have it call back the method of the original bean. To do this each bean needed a reference to the other -- thus circular. @Inject
failed for this task whereas @EJB
worked.
@Inject
can inject any bean, while @EJB
can only inject EJBs. You can use either to inject EJBs, but I'd prefer @Inject
everywhere.