Java Reference
In-Depth Information
Using the @EJB annotation is very powerful and allows the container to do the work of
looking up beans and injecting them into classes instead of you having to do the JNDI look-
ups yourself. The @EJB annotation is a special subset of DI that only handles EJBs. There
are other resources, such as JDBC data sources, JMS queues, and email sessions, which
the container manages and your code needs to get at. In the next session we'll discuss the
@Resource annotation for injecting these other resources.
Injection using proxy objects
When a container injects an EJB, what really gets injected? The answer is a proxy object.
The container creates a proxy object for your bean and injects the proxy, not the bean class
itself. The container does this so it can properly manage all the services that EJBs provide,
such as transactions and thread safety. The proxy also makes sure the correct underlying
bean is being accessed through the proxy. For example, suppose you have the following
simple stateless session bean:
@Stateless
public class BidService {
}
Because all references to this bean are assigned the same object identity by the container,
the proxy ensures the correct object is returned. You can use the equals() method to
check if this is true:
@EJB
BidService bid1;
@EJB
BidService bid2;
. . .
bid1.equals(bid2); // this will return true
On the other hand, suppose you have the following simple stateful session bean:
@Stateful
public class ShoppingCart {
}
In this case, the container is required to assign different identities to different stateful ses-
sion bean instances. The proxy handles this as well, so the equals() method can check
that these are two different carts:
Search WWH ::




Custom Search