JavaBeans
JavaBeans is a technology developed by Sun Microsystems and released in 1996, as part
of JDK 1.1.
The „beans‟ of JavaBeans are classes that encapsulate one or more objects into a single
standardized object (the bean). This in turn allows the beans to be treated as software
components, and to be manipulated visually by editors and IDEs without needing any initial
configuration, or to know any internal implementation details.
JavaBean Conventions (Rules)
The class must be public.
The class must implement java.io.Serialiazable.
The class must have a public default constructor with no arguments.
The class must define private properties.
For each properties, there must be accesor (getter) and mutator (setter) methods.
Rules for accesor (getter) method
It should be public in nature.
The return type shouldn‟t be void.
It needs to be prefixed with the word get.
It shouldn‟t take any argument.
Rules for mutator (setter) method
It should be public in nature.
Return Type needs to be void.
Setter Method needs to be prefixed using the word set.
It should take some argument.
Writing a simple java bean
import java.io.*;
public class Person implements Serializable {
//define bean properties
private String name;
private int age;
private double salary;
public Person() //default no-argument constructor
{
}
//define getters and setters
public void setName(String name)
{
this.name=name;
}
public void setAge(int age)
{
this.age=age;
}
public void setSalary(double salary)
{
this.salary=salary;
}
public String getName()
{
return this.name;
}
public int getAge()
{
return this.age;
}
public double getSalary()
{
return this.salary;
}
}
Note: The java bean class created above can be used in normal java applications as
well as in JSP.
Using in normal java application
public class Main {
public static void main(String [] args) {
Person p=new Person( );
p.setName(“Ram”);
p.setAge(35);
p.setSalary(25000);
System.out.println(“Name: ”+p.getName( ));
System.out.println(“Age: ”+p.getAge( ));
System.out.println(“Salary: ”+p.getSalary( ));
} }
Using in JSP
We should use following tags:
<jsp:useBean> -- for giving an “id” to the bean object
<jsp:setProperty> -- for calling the setter method
<jsp:getProperty> -- for calling the getter method
<html>
<body>
<jsp:useBean id= “per” class= “Person” />
<jsp:setProperty name= “per” property= “name” value= “Ram”/>
<jsp:setProperty name= “per” property= “age” value= “35”/>
<jsp:setProperty name= “per” property= “salary” value= “35000”/>
Name: <jsp:getProperty name= “per” property= “name”/>
Age: <jsp:getProperty name= “per” property= “age”/>
Salary: <jsp:getProperty name= “per” property= “salary”/>
</body>
</html>
Advantages of JavaBeans
1. Exposure to other applications
One of the most important advantages of a JavaBean is, the events properties and the methods of a bean
can be exposed directly to another application.
2. Registration to receive events
A JavaBean can be registered to receive events from other objects. However, we can also generate events
that can be sent to other objects.
3. Ease of configuration
We can easily use auxiliary software to configure the JavaBean. However, we can also save the
configuration setting of a JavaBean to persistent storage.
4. Portable
As JavaBeans are built in Java, we can easily port them to any other platform that contains JRE (Java
Runtime Environment).
5. Lightweight
JavaBeans are light weighted, i.e. we don't need to fulfill any special requirement to use it. Also, it is very
easy to create them.
Disadvantages of JavaBeans
1. JavaBeans are mutable, hence lack the advantages offered by immutable objects.
2. Creating a setter and getter for each property in a class may lead to a boilerplate code.
Basic Bean Concepts/Features of a Bean
Introspection
Is the ability of a JavaBean to allow an external application to query the properties,
methods, and events supported by it.
Properties
A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples
of bean properties include color, label, font, font size, and display size.
Customization
The exposed properties of a Bean can be customized at design time. It allows the user to
change the appearance and behavior of a bean.
Events
Beans use events to communicate with other beans. Beans may fire events. The bean which
fires the event is called source bean and the bean that receive the event is called listener bean. A
listener bean registers its interest in the event with the source bean. Builder tools use
introspection to determine those events that a Bean sends and those events that it receives.
Persistence
Is the ability of JavaBean to save its state to disk or storage device and restore the saved state
when the JavaBean is reloaded. Beans use object serialization implementing the java.io.Serializable
interface.
Methods
Java beans contain getter (accessor) and setter (mutator) methods which are public in nature.
All these public methods can be identified using introspection mechanism.
Java Beans Builder Tool
Builder tools allow a developer to work with JavaBeans in a convenient way. By examining a
JavaBean by a process known as Introspection, a builder tool exposes the discovered features of
the JavaBean for visual manipulation. A builder tool maintains a list of all JavaBeans available.
It allows you to compose the Bean into application (e.g. a JFrame), customize its behavior and
appearance by modifying its properties and connect other components to the event of the Bean.
Note: Netbeans is the mostly used builder tool recently.
Introspection
Introspection can be defined as the technique of obtaining information about bean
properties, events and methods.
Basically introspection means analysis of bean capabilities.
Introspection is the automatic process by which a builder tool finds out which properties,
methods, and events a bean supports.
Introspection describes how methods, properties, and events are discovered in the beans
that you write.
This process controls the publishing and discovery of bean operations and properties
Properties (Java Bean Properties)
A bean property is a named attribute of a bean that can affect its behavior or appearance. Examples
of bean properties include color, label, font, font size, and display size.
Properties are the private data members of the JavaBean classes.
Properties are used to accept input from an end user in order to customize a JavaBean.
Properties can retrieve and specify the values of various attributes, which determine the behavior of a
JavaBean.
Types of JavaBeans Properties
Simple Property
Indexed Property
Bound property
Simple Property: A bean property with a single value whose changes are independent of changes in
any other property is called simple property. To add simple property to a bean, we use appropriate
getters(getXXX( )) and setters (setXXX( )). For simple property of type “Boolean” we use setXXX( )
and isXXX( ).
For example, suppose we have two properties:
private int age;
private boolean voter;
The getters and setter for these two properties would be:
public void setAge(int age) { this.age=age;}
public void setVoter(boolean voter) { this.voter=voter;}
public int getAge( ) { return age; }
public boolean isVoter( ) { return voter; }
Indexed Property: A bean property that supports a range of values instead of a single value is called
indexed property. Indexed Properties enable you to set or retrieve the values from an array of
property values.
//Methods to access the entire indexed property array
public <PropertyType>[] get<PropertyName>();
public void set<PropertyName>(<PropertyType>[] value);
//Methods to access individual values
public <PropertyType> get<PropertyName>(int index);
public void set<PropertyName>(int index, <PropertyType> value);
Bound Property: A bean that has a bound property generates an event when the property is
changed. Bound Properties are the properties of a JavaBean that inform its listeners about changes in
its values. Bound Properties are implemented using the PropertyChangeSupport class and its
methods. Bound Properties are always registered with an external event listener.
The event is of type PropertyChangeEvent and is sent to objects that previously registered an
interest in receiving such notifications
bean with bound property - Event source
Bean implementing listener -- event target
In order to provide this notification service a JavaBean needs to have the following two methods:
public void addPropertyChangeListener(PropertyChangeListener p) {
changes.addPropertyChangeListener(p);
}
public void removePropertyChangeListener(PropertyChangeListener p) {
changes.removePropertyChangeListener(p);
}
Constrained Properties:
A bean property for which a change to the property results in validation by another bean. The other
bean may reject the change if it is not appropriate.
Constrained Properties are the properties that are protected from being changed by other JavaBeans.
Constrained Properties are registered with an external event listener that has the ability to either
accept or reject the change in the value of a constrained property.
Constrained Properties can be retrieved using the get method. The prototype of the get method is:
Syntax:public string get<ConstrainedPropertyName>()
Can be specified using the set method. The prototype of the set method is:
Syntax :public string set<ConstrainedPropertyName>(String str)throws PropertyVetoException
Persistence
Persistence means an ability to save properties and events of our beans to non-volatile storage and
retrieve later.
It has the ability to save a bean to storage and retrieve it at a later time Configuration settings are
saved It is implemented by Java serialization.
If a bean inherits directly or indirectly from Component class it is automatically Serializable.
Transient keyword can be used to designate data members of a Bean that should not be serialized.
Java Beans supports two forms of persistence:
Automatic persistence
External persistence
Automatic Persistence:
Automatic persistence are java‟s built-in serialization mechanism to save and restore the state of a
bean.
External Persistence:
External persistence, on the other hand, gives you the option of supplying your own custom classes
to control precisely how a bean state is stored and retrieved.
Customizers:
The Properties window of the BDK(Bean Development Kit) allows a developer to modify the several
properties of the Bean.
It can provide step-by-step wizard guide to use component
It can provide a GUI frame with image which visually tells what is changed such as radio button,
check box etc.
It can customize the appearance and behavior of the properties
Online documentation can also be provided. A Bean developer has great flexibility to develop a
customizer that can differentiate his or her product in the marketplace.
Enables a developer to use an application builder tool to customize the appearance and behavior of a
bean.
The BeanInfo Interface :
By default an Introspector uses the Reflection API to determine the features of a JavaBean.However,
a JavaBean can provide its own BeanInfo which will be used instead by the Introspector to determine
the discussed information. This allows a developer hiding specific properties, events and methods
from a builder tool or from any other tool which uses the Introspector class. Moreover it allows
supplying further details about events/properties/methods as you are in charge of creating the
descriptor objects. Hence you can, for example,call the setShortDescription() method to set a
descriptive description. A BeanInfo class has to be derived from the SimpleBeanInfo class and its
name has to start with the name of the associated JavaBean. At this point it has
to be underlined that the name of the BeanInfo class is the only relation between a JavaBean and its
BeanInfo class.
The BeanInfo interface provides the methods that enable you to specify and retrieve the information
about a JavaBean.
The following table lists some of the methods of BeanInfo interface:
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.io.*;
public class Main {
public static void main(String[] argv) throws Exception {
BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
MethodDescriptor[] mds = bi.getMethodDescriptors();
System.out.println("Method Descriptors");
for (int i = 0; i < mds.length; i++) {
String methodName = mds[i].getDisplayName();
System.out.println(methodName);
}
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
System.out.println("Property Descriptors");
for (int i = 0; i < pds.length; i++) {
String propName = pds[i].getDisplayName();
System.out.println(propName);
}
}
}
class MyBean implements Serializable {
private int id;
private String name;
public MyBean(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id=id;
}}
The Java Beans API
The Java Beans functionality is provided by a set of classes and interfaces in
the java.beans package. This section provides a brief overview of its contents.