Prev | Next

TOC | Index

J2EETM Developer's Guide
Session Beans


Accessing Environment Entries

Note: The material described in this section applies to both session and entity beans.

Stored in an enterprise bean's deployment descriptor, an environment entry is a name-value pair that allows you to customize the bean's business logic without changing its source code. An enterprise bean that calculates discounts, for example, might have an environment entry named "Discount Percent." Before deploying the bean's application, you could assign "Discount Percent" a value of .05 on the Environment tabbed pane of the Application Deployment Tool. When you run the application, the enterprise bean fetches the .05 value from its environment.

In the following code example, the applyDiscount method uses environment entries to calculate a discount based on the purchase amount. First, the method locates the environment naming context by invoking lookup with the "java:comp/env" parameter. Then it calls lookup on the environment to get the values for the "Discount Level" and "Discount Percent" names. If you had assigned a value of .05 to the "Discount Percent" name in the Application Deployment Tool, the code will assign .05 to the discountPercent variable. The full source code for the enterprise bean that contains the applyDiscount method is in the CheckerEJB class.

public double applyDiscount(double amount) {

      try {

         double discount;
   
         Context initial = new InitialContext();
         Context environment = 
           (Context)initial.lookup("java:comp/env");
   
         Double discountLevel = 
            (Double)environment.lookup("Discount Level");
         Double discountPercent = 
            (Double)environment.lookup("Discount Percent");
   
         if (amount >= discountLevel.doubleValue()) {
            discount = discountPercent.doubleValue();
         }
         else {
            discount = 0.00;
         }
    
         return amount * (1.00 - discount);

      } catch (NamingException ex) {
           throw new EJBException("NamingException: " +
              ex.getMessage());
      }
   }



Prev | Next

TOC | Index


Copyright © 2000 Sun Microsystems, Inc. All rights reserved.