What are Java Beans?
Java Beans are reusable so ware components that adhere to a specific set of conven ons and
guidelines defined by Sun Microsystems (now Oracle). They are essen ally Java classes that
encapsulate data and func onality, making them easily accessible and manageable. Java Beans
follow the principle of “Write Once, Run Anywhere” and can be integrated seamlessly into various
Java development frameworks.
Characteris cs of JavaBeans:
1. Must be a public class:
public class StudentBean {
2. Must have a no-argument constructor:
public StudentBean() {
3. Proper es must follow ge er/se er conven on:
private String name;
public String getName() {
return name;
public void setName(String name) {
[Link] = name;
4. Must implement Serializable interface
import [Link];
public class StudentBean implements Serializable {
}
Example of a Java Beans Class :
// Java Program of JavaBean class
public class Student implements [Link] {
private int id;
private String name;
// Constructor
public Student() {}
// Se er for Id
public void setId(int id) { [Link] = id; }
// Ge er for Id
public int getId() { return id; }
// Se er for Name
public void setName(String name) { [Link] = name; }
// Ge er for Name
public String getName() { return name; }
Why JavaBeans were introduced?
Before JavaBeans:
Code reuse was difficult
No standard component model
No tool support for visual programming
No easy integra on
A er JavaBeans:
Standard reusable components
Tool-based development
Visual design support
Enterprise applica on compa bility
Advantages of Java Beans:
JavaBeans are reusable so ware components that follow specific design conven ons, such as having
a public no-argument constructor and private fields accessed via public ge er and se er methods.
Their architecture provides several key benefits:
1)Reusability and Modularity: They allow developers to create self-contained components that can
be "plugged in" to different parts of an applica on or reused across en rely different projects,
reducing code duplica on and saving development me.
Example :
A single StudentBean → used in:
- College Management System
- ERP System
- A endance System
2) Standardiza on and Tool Support: By adhering to the JavaBeans specifica on, these components
are compa ble with various IDEs (like Eclipse or NetBeans) and visual builder tools. This enables
"Introspec on," where tools can automa cally discover and manipulate a bean's proper es, events,
and methods.
3)Encapsula on: JavaBeans promote strong data encapsula on by hiding internal state behind
private fields. Controlled access via ge ers and se ers ensures data integrity and allows for
valida on logic before property changes are applied.
4)Persistence and State Management: Most JavaBeans implement the Serializable interface,
allowing their state to be saved (to a file or database) and restored later. This is crucial for session
management in web applica ons and persistent user se ngs.
5)Pla orm Independence: Inheri ng Java’s "Write Once, Run Anywhere" nature, JavaBeans are
highly portable and can run on any pla orm that supports a Java Run me Environment (JRE).
6)Event Handling: JavaBeans support a standard event model, allowing them to register for and fire
events. This facilitates decoupled communica on between components, which is par cularly useful
in crea ng responsive Graphical User Interfaces (GUIs).
7)Easier Maintenance: Because beans encapsulate many objects into a single unit, they simplify data
management and make large-scale enterprise applica ons easier to maintain and test.
JAVA BEAN API
JavaBeans API is a collec on of classes in the [Link] package that helps us create, manage, and
control JavaBeans. All the concepts we study , like proper es, events, BeanInfo ,come from this API.
[Link]
Introspector
PropertyDescriptor
PropertyChangeListener
VetoableChangeListener
BeanInfo etc..
Bean Development kit :
The Bean Development Kit (BDK) is a toolkit provided by Java that enables developers to create, test,
and manipulate JavaBeans components in a visual environment.
Purpose of BDK
BDK is used to:
Test JavaBeans visually
Connect different beans
Observe property changes
Handle events between beans
Simulate component-based development
Component of BDK
[Link] Box:
Lists a sample Java Beans of bdk
2. BeanBox Window:
Workspace for crea ng layout for java bean applica on
3. Proper es Window:
Display all the exposed proper es of a JavaBean. You Can Modify Javabean proper es in the
proper es window.
4. Method Tracer:
Display the debugging messages and method calls for a JavaBeans applica on.
Features of BDK
1. Visual Programming
o Beans can be dragged and dropped
2. Event Handling
o Beans can communicate using events
3. Property Edi ng
o Proper es can be modified using GUI
4. Tes ng Environment
o Allows tes ng without wri ng full programs
5. Component Interac on
o Mul ple beans can interact with each other
Advantages of BDK
Simplifies JavaBean development
No need for complex coding
Visual tes ng of beans
Helps in debugging
Supports rapid prototyping
🔹 Limita ons of BDK
Limited to basic tes ng
Not used in modern enterprise tools
GUI is outdated
Not suitable for large applica ons
Introspec on:
“Introspec on is a mechanism by which Java examines a bean class at run me to iden fy its
proper es, methods, and events without explicit configura on.”
builder tools typically provide a property sheet where one can conveniently set the proper es of a
JavaBean component.
In order to provide this service a builder tool needs to examine the component for its features
(proper es, events and methods).This process is referred to as "introspec on".
“Introspec on is the automa c process of analyzing bean's design pa erns to reveal the bean's
proper es, events, and methods. This process controls the publishing and discovery of bean
opera ons and proper es.”
Types of Introspec on
Implicit Introspec on:
Done automa cally by Java
Uses naming conven ons
“This is the "automa c" way. The Java Introspector class uses low-level reflec on to analyze a class
and infer its capabili es based on standard design pa erns or naming rules”
Java beans use naming conven on:
Method Type Naming Rule
Ge er getPropertyName()
Se er setPropertyName()
Boolean Ge er isPropertyName()
Example:
public String getName();
public void setName(String name);
The introspector automa cally assumes there is an Name property.
Explicit Introspec on
Done using BeanInfo interface
Developer manually defines proper es
To obtain informa on about a specific JavaBean one can use the sta c getBeanInfo() method of the
Introspector class.
This method returns an instance of the BeanInfo class, which describes all features a JavaBean
exposes.
Bound Property:
A Bound Property is an a ribute of a JavaBean that no fies other objects (listeners) when its value
changes. This is a fundamental concept in event-driven programming, allowing a "Source" object to
stay in sync with "Target" objects without being ghtly coupled to them.
Some mes when a Bean property changes, another object may want to be no fied of the change,
and react to the change. Whenever a bound property changes, no fica on of the change is sent to
interested listeners.
Key Technical Concepts
Source Bean: The class containing the property. It maintains a list of interested listeners.
PropertyChangeListener:
The PropertyChangeListener interface is used by any class that needs to be no fied of
changes to a bound property. It acts as the "observer" or "subscriber" that waits for an
update from an event source.
It defines a single method, propertyChange(PropertyChangeEvent evt).
It receives the PropertyChangeEvent object, allowing the listener to inspect the property
name, the old value, and the new value to determine how to respond.
PropertyChangeEvent:
The PropertyChangeEvent class encapsulates property change informa on, and is sent from
the property change event source to each object in the property change listener list via the
propertyChange method.
The object delivered to listeners. It carries three vital pieces of data:
1. The name of the property.
2. The old value.
3. The new value.
PropertyChangeSupport: A u lity class provided by Java ([Link]) that handles the heavy
li ing of managing listeners and firing events.
The convenience class PropertyChangeSupport implements methods that add and
remove PropertyChangeListener objects from a list, and fires PropertyChangeEvent objects
at those listeners when the bound property changes.
Example: scenario:
A Bank Account has a balance
Whenever balance changes
A No fica on System shows the update
JavaBeans
Bank Balance Property
Bank Account JavaBean
No fica on System Listener
Message Event
Event system PropertyChangeSupport
CODE:
JavaBean (BankAccount)
import [Link].*;
public class BankAccount {
private int balance;
private PropertyChangeSupport support; // This object maintains the property change listener
list and fires property change events.
public BankAccount() {
support = new PropertyChangeSupport(this); //ini aliza on of the support object when then
bean object is created
//following sec on Implement methods to maintain the property change listener list, which is
implemented by PropertyChangeSupport
public void addPropertyChangeListener(PropertyChangeListener
listener) {
[Link](listener);
public void removePropertyChangeListener(PropertyChangeListener
listener)
public int getBalance() {
return balance;
// next sec on : Modify a property's se er method to fire a property change event when the
property is changed.
public void setBalance(int newBalance) {
int oldBalance = [Link];
[Link] = newBalance;
// 🔥 Event fired here
support.firePropertyChange("balance", oldBalance,
newBalance);
}
}
Listener (No fica on System)
import [Link].*;
public class BankListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// This method needs to contain the code that handles what you need to do when the listener
receives property change event.
[Link]("Balance Updated!");
[Link]("Old Balance: " + [Link]());
[Link]("New Balance: " + [Link]());
Main Class
public class TestBank {
public sta c void main(String[] args) {
BankAccount account = new BankAccount();
BankListener listener = new BankListener();
// Register listener
[Link](listener);
// Change property
[Link](1000);
[Link](2000);
}
OUTPUT:
Balance Updated!
Old Balance: 0
New Balance: 1000
Balance Updated!
Old Balance: 1000
New Balance: 2000
For Extra info on bound proper es read this ar cle :
h ps://[Link]/esc101/05Aug/tutorial/javabeans/proper es/[Link]
Applica ons of Bound Proper es
UI Synchroniza on: Automa cally upda ng a progress bar or label when background data
changes.
Automated Refreshing: Triggering a dashboard to redraw itself the moment a database
value updates.
State Monitoring: Tracking the status of a background task (e.g., switching from "Loading" to
"Complete").
Constrained Property:
A Bean property is constrained when any change to that property can be vetoed(Rejected).
Usually an outside object exercises the right to veto, but the Bean itself can also veto a property
change
The JavaBeans API provides an event mechanism, very similar to the bound property mechanism,
that allows objects to veto a Bean's property changes.
There are three parts to constrained property implementa ons:
A source Bean containing one or more constrained proper es.
Listener objects that implement the VetoableChangeListener interface. This object accepts or
rejects proposed changes to a constrained property in the source Bean.
A PropertyChangeEvent object containing the property name, and its old and new values.
This is the same class used for bound proper es.
VetoableChangeListener interface
VetoableChangeSupport class
PropertyChangeEvent class
PropertyVetoException class
Key Technical Components:
Source Bean:
The class containing the constrained property.
Its setter methods must declare that they can throw a PropertyVetoException.
VetoableChangeListener (The Validator):
An interface implemented by any class that wants the power to accept or reject changes.
It defines a single method: vetoableChange(PropertyChangeEvent evt) throws
PropertyVetoException.
If the listener's logic determines the newValue is invalid, it throws the exception to stop the
process.
PropertyVetoException (The Rejection):
The specific exception thrown by a VetoableChangeListener to signal that the proposed
property change is unacceptable.
VetoableChangeSupport (The Helper):
A utility class in [Link] that manages the list of VetoableChangeListeners and fires the
vetoable events.
It operates exactly like PropertyChangeSupport, but uses the method fireVetoableChange().
EXAMPLE:
Scenario:
Consider a Bank Account system where a user tries to update their account balance.
The system must ensure that the balance does not become nega ve.
Before upda ng the balance, the system checks the new value using a listener.
If the new balance is nega ve, the change is rejected by throwing an excep on.
CODE:
Bean Class
import [Link].*;
public class BankAccount {
private int balance; //Constrained Property
private VetoableChangeSupport support;
//VetoableChangeSupport manages a list of VetoableChangeListener objects, and fires property
change events at each object in the list when a change occurs to a constrained property.
public BankAccount() {
support = new VetoableChangeSupport(this); //ini alizing the veto support object at me of
bean object crea on
//following sec on: Implement methods to maintain the property change listener list. These merely
wrap calls to the VetoableChangeSupport object's methods
public void addVetoableChangeListener(VetoableChangeListener listener) {
[Link](listener);
public void removeVetoableChangeListener(VetoableChangeListener
listener){
[Link](listener);
public int getBalance() {
return balance;
}
// Write a property's se er method to fire a property change event when the property is changed.
public void setBalance(int newBalance) throws PropertyVetoExcep on {
int oldBalance = [Link];
// 1. FIRE EVENT FIRST (Ask for permission before changing)
support.fireVetoableChange("balance", oldBalance, newBalance);
// 2. IF no excep on was thrown by listeners, apply the change
[Link] = newBalance;
Listener Class(The validator)
import [Link].*;
public class BankChecker implements VetoableChangeListener {
@Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoExcep on {
int newBalance = (int) [Link]();
//checks if the balance is nega ve if yes then throws excep on
if (newBalance < 0) {
throw new PropertyVetoExcep on("Balance cannot be nega ve!", evt);
}
Main Class
public class TestConstrained {
public sta c void main(String[] args) {
try {
BankAccount account = new BankAccount();
[Link](new BankChecker());
[Link](1000); // allowed
[Link](-500); // rejected
} catch (Excep on e) {
[Link]([Link]());
Output:
Balance cannot be nega ve!
FOR Extra info on constrained proper es visit :
h ps://[Link]/esc101/05Aug/tutorial/javabeans/proper es/constraine
[Link]
Bean Info Interface:
How does a builder tool examine a Bean and expose its features (proper es, events, and
methods) in a property sheet?
By using the [Link] class.
The Introspector class uses the JDK core reflec on API to discover a Bean's methods, and then
applies the JavaBeans design pa erns to discover the Beans features. This discovery process is
named introspec on.
Defini on:
The BeanInfo interface (part of the [Link] package) allows a developer to explicitly define
and control which proper es, events, and methods of a JavaBean are exposed to visual builder
tools (like the BDK or modern IDEs).
By associa ng a BeanInfo class with your Bean, you can:
Expose only those features you want to expose.
Rely on BeanInfo to expose some Bean features while relying on low-level reflec on to
expose others.
Specify a customizer class.
Segregate features into normal and expert categories.
Provide a more descrip ve display name, or addi onal informa on about a Bean feature.
Key Technical Components
1. The BeanInfo Interface & SimpleBeanInfo Class
o Implemen ng the full BeanInfo interface from scratch is tedious because it requires
defining many methods.
o Instead, developers typically extend the SimpleBeanInfo helper class and override
only the specific methods they want to customize (like getPropertyDescriptors()).
2. Naming Conven on Requirement
o For the Java Introspector to find your custom rules, the class name must be the exact
name of your Bean with the word "BeanInfo" appended to it.
o Example: If your Bean is Student, the custom class must be named StudentBeanInfo.
3. Feature Descriptors
BeanInfo defines methods that return descriptors for each property, method, or event that
you want exposed. Here's the snippet for these methods:
PropertyDescriptor[ ] getPropertyDescriptors( );
MethodDescriptor[ ] getMethodDescriptors( );
EventSetDescriptor[ ] getEventSetDescriptors( );
Each of these methods returns an array of descriptors for each feature.
4. The Introspector Class
o When a tool wants to inspect a Bean, it calls [Link]([Link]).
o The Introspector first looks for a StudentBeanInfo class. If it finds one, it uses those
explicit rules. If it doesn't, it falls back to implicit (automa c) introspec on.
Feature Descriptors
BeanInfo classes contain descriptors that precisely describe the target Bean's features. The BDK
implements the following descriptor classes:
FeatureDescriptor is the base class for the other descriptor classes. It declares the aspects
common to all descriptor types.
BeanDescriptor describes the target Bean's class type and name, and describes the target
Bean's customizer class if it exists.
PropertyDescriptor describes the target Bean's proper es.
IndexedPropertyDescriptor is a subclass of PropertyDescriptor, and describes the target
Bean's indexed proper es.
EventSetDescriptor describes the events the target Bean fires.
MethodDescriptor describes the target Bean's methods.
ParameterDescriptor describes method parameters.
The BeanInfo interface declares methods that return arrays of the above descriptors.
EXAMPLE
Scenario:
A Student bean has name, age, and a sensi ve password. We use BeanInfo to explicitly expose only
the name and age, hiding the password from builder tools
CODE:
JavaBean Class
public class StudentBean {
private String name;
private int age;
private String password;
public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public int getAge() { return age; }
public void setAge(int age) { [Link] = age; }
public String getPassword() { return password; }
public void setPassword(String password) { [Link] = password; }
}
BeanInfo Class
import [Link] onExcep on;
import [Link];
import [Link];
// 1. Class name MUST be BeanName + "BeanInfo"
public class StudentBeanInfo extends SimpleBeanInfo {
// 2. Override the method that defines exposed proper es
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
try {
// Explicitly define only the proper es we want to show
PropertyDescriptor nameProp = new PropertyDescriptor("name", [Link]);
PropertyDescriptor ageProp = new PropertyDescriptor("age", [Link]);
// Return them as an array (No ce 'password' is not included)
return new PropertyDescriptor[] { nameProp, ageProp };
} catch (Introspec onExcep on e) {
[Link]();
return null;
}
}
}
Advantages
Provides full control
Overrides default behavior
Improves customiza on
Useful in GUI tools
Limita ons
Extra coding required
Less used in modern frameworks
Can be complex
For extra info on BeanInfo interface visit
h ps://[Link]/esc101/05Aug/tutorial/javabeans/beaninfo/[Link]
BEAN Customiza on:
Customiza on provides a means for modifying the appearance and behavior of a bean
within an applica on builder so it meets your specific needs. There are several levels of
customiza on available for a bean developer to allow other developers to get maximum
benefit from a bean's poten al func onality.
A Bean's appearance and behavior can be customized at design me within Beans-compliant
builder tools. Typically there are two ways to customize a Bean:
By using a property editor. Each Bean property has its own property editor. A builder
tool usually displays a Bean's property editors in a property sheet. A property editor
is associated with, and edits a par cular property type.
By using customizers. Customizers give you complete GUI control over Bean
customiza on. Customizers are used where property editors are not prac cal or
applicable. Unlike a property editor, which is associated with a property, a customizer
is associated with a Bean.
Property Editors
A property editor is a tool for customizing a par cular property type. Property editors are
ac vated in the Proper es window. This window determines a property's type, searches for
a relevant property editor, and displays the property's current value in a relevant way.
Property editors must implement the PropertyEditor interface, which provides methods to
specify how a property should be displayed in a property sheet.
Customizers
When you use a Bean Customizer, you get complete control over how to configure or edit a
Bean. A Customizer is like an applica on that specifically targets a Bean's customiza on.
Some mes proper es are insufficient for represen ng a Bean's configurable a ributes.
Customizers are used where sophis cated instruc ons would be needed to change a Bean,
and where property editors are too primi ve to achieve Bean customiza on.
All customizers must:
Extend [Link] or one of its subclasses.
Implement the [Link] interface This means implemen ng methods
to register PropertyChangeListener objects, and firing property change events at
those listeners when a change to the target Bean has occurred.
Implement a default constructor.
Associate the customizer with its target class via [Link].
h ps://[Link]/javase/tutorial/javabeans/advanced/customiza [Link]
Enterprise JavaBeans (EJB)
Enterprise JavaBeans (EJB) is a server-side component architecture for Java Pla orm,
Enterprise Edi on (Java EE). While standard JavaBeans are meant for simple client-side data
encapsula on and UI, EJBs are designed to encapsulate the core business logic of an
enterprise applica on. They run on a centralized server and are highly scalable, secure, and
robust.
Why were EJBs introduced?
Before EJB: Developers wri ng enterprise applica ons had to manually write
complex "plumbing" code for transac on management, security, database
connec on pooling, and mul threading. This made applica ons bulky and hard to
maintain.
A er EJB: The EJB architecture introduced the EJB Container. Developers now only
write the business logic. The Container automa cally handles the complex system-
level services (security, transac ons, concurrency).
Characteris cs & Advantages of EJB:
1. Container-Managed Services: The EJB container manages lifecycle, security, and
transac on handling.
2. Scalability: EJBs can be distributed across mul ple servers to handle heavy loads.
3. Pla orm Independence: Like standard Java, EJBs are "Write Once, Run Anywhere"
across any Java EE-compliant server (e.g., GlassFish, JBoss/WildFly, WebLogic).
4. Security: EJBs support declara ve security, allowing administrators to restrict access
to certain methods using annota ons or XML configura ons.
EJB Architecture (Key Components)
Examiners look for an understanding of the three- er architecture in EJB:
1. EJB Client: The applica on (like a web browser, a mobile app, or a desktop GUI) that
requests a service. It does not run the business logic; it simply calls the bean.
2. EJB Container: The run me environment provided by the applica on server. It wraps
around the EJB and intercepts all client requests to inject services (like checking if the
user has security permissions) before passing the request to the bean.
3. EJB Server: The physical or virtual machine hos ng the Applica on Server and the
Container.
Types of Enterprise JavaBeans
There are two primary types of EJBs used in modern enterprise applica ons:
1. Session Beans
Session beans execute tasks for a specific client. They encapsulate business logic that can be
invoked programma cally. They are divided into three sub-types:
Stateless Session Bean:
o Does not maintain a conversa onal state with the client.
o Once a method execu on is complete, the bean forgets the client.
o Highly efficient and uses fewer server resources.
o Example: A currency converter or a tax calculator.
Stateful Session Bean:
o Maintains a conversa onal state with a specific client across mul ple method
calls.
o The bean is dedicated to one client for the dura on of the session.
o Example: A shopping cart on an e-commerce website (it must remember
what was added in step 1 during step 3).
Singleton Session Bean:
o Only one single instance of this bean is instan ated per applica on.
o It is shared concurrently among all clients.
o Example: A hit counter for a website or a global configura on manager.
2. Message-Driven Beans (MDB)
Unlike Session Beans, which are called directly (synchronously), MDBs operate
asynchronously.
A client sends a message to a messaging queue (using Java Message Service - JMS)
and immediately con nues its work. The MDB listens to the queue and processes the
message in the background when it is ready.
Example: Genera ng a complex monthly PDF report or sending an order
confirma on email.
3. En ty Bean: An En ty Bean represents persistent data stored in a rela onal database. If a
Session Bean is the "ac on" (business logic), the En ty Bean is the "data" (like a single row in
a database table).
(i) Bean Managed Persistence :
In a bean managed persistence type of en ty bean, the programmer has to write the
code for database calls. It persists across mul ple sessions and mul ple clients.
(ii) Container Managed Persistence :
Container managed persistence are enterprise bean that persists across database. In
container managed persistence the container take care of database calls.