JavaBeans Component Design Conventions



JavaBeans Component Design Conventions

JavaBeans component design conventions govern the properties of the class, and the public methods that give access to the properties.

A JavaBeans component property can be:

  • Read/write, read-only, or write-only.

  • Simple, which means it contains a single value, or indexed, which means it represents an array of values.

There is no requirement that a property be implemented by an instance variable; the property must simply be accessible using public methods that conform to certain conventions:

  • For each readable property, the bean must have a method of the form: PropertyClass getProperty() { ... }

  • For each writable property, the bean must have a method of the form:

  • setProperty(PropertyClass pc) { ... }

In addition to the property methods, a JavaBeans component must define a constructor that takes no parameters.

The Duke'sBookstore application JSP pages enter.jsp, bookdetails.jsp, catalog.jsp, showcart.jsp use the database.BookDB and database.BookDetails JavaBeans components. BookDB provides a JavaBeans component front end to the access object BookDBAO. Both beans are used extensively by bean-oriented custom tags (see Custom Tags in JSP Pages (page 431)). The JSP pages showcart.jsp and cashier.jsp use cart.ShoppingCart to represent a user's shopping cart.

The JSP pages catalog.jsp, showcart.jsp, and cashier.jsp use the util.Currency JavaBeans component to format currency in a locale-sensitive manner. The bean has two writable properties, locale and amount, and one readable property, format. The format property does not correspond to any instance variable, but returns a function of the locale and amount properties.


public class Currency {
    private Locale locale; 
    private double amount; 
    public Currency() {
        locale = null; 
        amount = 0.0; 
    } 
    public void setLocale(Locale l) {
        locale = l; 
    } 
    public void setAmount(double a) {
        amount = a; 
    } 
    public String getFormat() {
        NumberFormat nf = 
            NumberFormat.getCurrencyInstance(locale); 
        return nf.format(amount); 
    } 
}