Java Reference
In-Depth Information
5.2.14. EJB versus CDI injection
The
@EJB
annotation is a fast, easy, and powerful way to have the EE server inject EJBs
into managed resources for you. The
@EJB
annotation was a great step forward for simpli-
fying Enterprise development and introducing DI to the EJB container. But
@EJB
is lim-
ited to injecting only EJBs and only into managed resources like other EJBs, JSF-backing
beans, and Servlets. CDI, on the other hand, is much more powerful and
@Inject
can in-
ject just about anything into anything else. This includes the ability for
@Inject
to inject
EJBs. Because
@Inject
is more powerful and can inject EJBs, why use
@EJB
?
For simple cases,
@EJB
and
@Inject
are interchangeable. Suppose ActionBazaar's
SimpleBidService
is a stateless no-interface EJB, which is as simple as you can get:
@Stateless
public class SimpleBidService {
...
}
In this case,
@EJB
and
@Inject
can be used exactly the same way and produce exactly
the same results:
@Inject
SimpleBidService bidService;
@EJB
SimpleBidService bidService;
But anything beyond this simple example and CDI starts to have a few problems. For ex-
ample, suppose
BidService
becomes an interface with multiple implementations:
public interface BidService { ... }
@Stateless(name="defaultBids")
public class DefaultBidService implements BidService { ... }
@Stateless(name="clearanceBids")
public class ClearanceBidService implements BidService { ... }
@EJB
handles this nicely in a few ways, but the easiest is to use the
beanName
parameter:
@EJB(beanName="clearanceBids")
BidService clearanceBidService;