Java Reference
In-Depth Information
5.2.5. @EJB annotation in action
The @EJB annotation is very easy to put into action. It is also very powerful because it has
smart defaults which allows you to quickly wire EJB injection with very little effort but it
also has the flexibility to handle unique situations where the defaults are not enough and
you need to provide some customization for your injections. What follows next are some
examples showing how to put the @EJB annotation into action.
Default injection
Suppose you have the following local interface and implementing bean:
@Local
public interface AccountLocal {
public void Account getAccount(String accountId);
}
@Stateless(name="accountByDatabase")
public class AccountByDatabaseEjb implements AccountLocal {. . .}
To inject this bean into a container-managed resource, such as a Servlet, you can use the
@EJB annotation without any of the optional elements and let the container figure out the
DI:
@EJB
AccountLocal accountInfo;
In this example, the container will detect the @EJB annotation and see that the injected
bean needs to implement the AccountLocal interface. The container will look through
its registered beans and inject an instance of AccountByDatabaseEjb because that
bean implements the required interface.
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 {. . .}
Search WWH ::




Custom Search