Java Reference
In-Depth Information
5.2.9. Looking up resources and EJBs from JNDI
Although you can use the @EJB or @Resource annotations to inject resource instances,
you may still need to look up items from JNDI in several advanced cases. There are two
ways of using programmatic lookups—with either the EJBContext or a JNDI Ini-
tialContext . We'll look at both methods.
EJBContext lookup
Recall from an earlier discussion that you're able to look up any object stored in JNDI us-
ing the EJBContext.lookup() method (including session bean references). This tech-
nique can be used to accomplish something extremely powerful: building lookups so re-
sources can be changed dynamically during runtime. Injection, though powerful, does con-
strain you to using static configuration that can't be changed programmatically.
Building lookups to dynamically get different resources at runtime is similar to dynamic-
ally building SQL statements. The difference is that instead of performing a query on a
database, you perform a lookup on JNDI. All you have to do is pass the dynamically gener-
ated name to the lookup method to retrieve a different resource. As a result, program logic
driven by data and/or user input can determine dependencies instead of deploy-time con-
figuration. The following code shows the EJBContext.lookup() method in action:
@Stateless
public class DefaultDiscountService implements DiscountService {
@Resource
private SessionContext sessionContext;
...
DiscountRateService discountRateService
= (DiscountRateService) sessionContext.lookup(
"java:app/ejb/HolidayDiscountRateService");
...
long discount = discountRateService.calculateDiscount(...);
This example shows how to look up a DiscountRateService using the Ses-
sionContext . Notice that the JNDI lookup string is part of the code and can easily be
dynamically changed to look up different implementations of DiscountRateService
based on any business rules. In this example, the EJB must be mapped to the java:app
namespace and the / ejb/HolidayDiscountRateService path.
Search WWH ::




Custom Search