Java Reference
In-Depth Information
with it through
AccountServices
. This is good practice if you want to have both re-
mote and local interactions to stay the same.
Injection using beanName
Now suppose your code base has more than one implementation of the
AccountLocal
interface. The previous example shows an implementation using a database; now let's add
an implementation that uses Active Directory:
@Stateless(name="accountByActiveDirectory")
public class AccountByActiveDirectoryEjb implements AccountLocal {. . .}
With multiple beans now implementing the
AccountLocal
interface, you need to give
the
@EJB
annotation a little help so the container knows which implementation should be
injected:
@EJB(beanName="accountByActiveDirectory")
AccountLocal accountInfo;
In this example, the container detects the
@EJB
annotation, and the value for
beanName
narrows down what implementation to inject. The container will find the bean with the
name
accountByActiveDirectory
, check that the bean implements the
Accoun-
tLocal
interface, and inject an instance of the
AccountByActiveDirectoryEjb
into the
accountInfo
variable.
Injection using lookup
Using the
lookup
attribute takes all the guesswork out of EJB injection. Instead of the
container trying to resolve the correct bean, you can tell the container exactly which bean
you want by specifying the actual JNDI name:
@EJB(lookup="java:module/DefaultAccountService")
AccountServices accountServices;
In this example, the container detects the
@EJB
annotation and the value for
lookup
nar-
rows down what to look up from JNDI and inject. You can use any naming scope that
makes sense.