Java Beans Explained in Detail

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 13

Java Beans

A COM-DCOM components in Visual Basic, are the components created


once & used many times, similarly Java Beans is the reusable piece of software
that can be assembled to create applications with much greater development
efficiency.
Java-bean is portable, platform independent component model written in
java programming language. Java beans architecture enables developers to
write reusable components in Java.
Java beans are being implemented as an architecture & platformindependent API for creating & using dynamic Java software components. Java
beans picks up where other component technologies have left off, using the
portable Java platform as the basis for providing a complete component software
solution that is readily applicable to the online world.
Application builder tools
A utility that enables you to config a set of beans., connect then together &
produce a working applet.
The major capabilities are
1. A palette is provided that lists all of available beans. New beans can be
added.
2. A worksheet is displayed that allows the designer to layout beans in a
Graphical User Interface.
3. Special editors & customizers allow a bean to config.
4. Commands allow a designer to enquire about state & behavior of bean.
5. Possible to save all of information.
Component Models
ComponentA component is an object that provides a set of services, or performs a
certain set of functions in a way that it can easily interact with other applications
or components.
- A component has certain states, attributes & methods.
- A component needs to be in a container.
- A component may also provide services to other components, and must
be independent of other components.
Defines architecture of components, which is responsible for determining
how components are able to interact in a dynamic environment & how they can
be manipulated & interacted with externally. Defines two elements are
Components & Containers. Also responsible for Introspection, Event handling,
Persistence, Layout, Application builder support, distributed computing support.

Features of Component Architecture- It is built upon a system of interacting components.


- Components can be added or removed to & from the system.
- Components are controlled consistently using a common interface.
Component Model Services / Beans specifications
The component model specified by the Java Bean, defines five major services1. Introspection- This process exposes the properties, methods & events that
a Java Bean component supports. It is used at runtime & while the bean is
being created with visual development tool.
2. Customization- One of the primary characteristics of a bean is its
reusability. The bean framework provides several ways of customizing
existing beans into new ones.
3. Component Packaging- Involves packaging different files into a single file.
This file will be available at runtime & will contain all resources required by
component(s). Resource may be image, html, audio files etc.
4. Distributed Computing- the ability of components running on different
machines to communicate. Distributes architecture enables developers to
tackle the problems by distributing the load and logic of an application
across many tiers effectively.
5. Persistence- Persistence is the means of storing the state of a component.
Persistence is achieved by serialization.
6. Event Handling- This event handling mechanism creates an event, which
serves as a message to other components. The source is the component
that sends or fires an event. The Listener is the component that receives
the event.
The technologies to develop reusable components1. COM
2. DCOM
3. ActiveX
4. CORBA (Common Object Request Broker)
5. Java Beans
JavaBeans Intro.
- Its development begin in 1995, & publicly available in 1996.
- Its a software component standard for Java platform.
- JavaBeans can be deployed on applets and stand-alone applications.
- A bean is a reusable, customizable software component written in pure
java. So they are like write once run anywhere
- Components created using JavaBeans architecture support properties,
events, methods, and persistence.
- Beans are linked through events.
- JavaBean supports automatic description of components through an
introspection mechanism.

Life cycle of a Bean


There are 3 phases of Life Cycle of Bean
1. Design- in this, bean is imported into builder tool for testing purpose. Here
it is customized, reused, persisted. The bean can be hooked with other
bean to achieve new functionality.
2. Development- in this, developer writes code for bean, using standards &
conventions of Java Beans specification.
3. Runtime- in this phase, bean is put into an applet or any application.
Bean Development Kit
Available from java soft site. It enables you to create, config & connect a
set of beans. Using BDK users can implement their own components as well as
describe interface specifications to their own components.
Almost any kind of java objects can be implemented as Java bean. Java
Bean is an integration technology, a component framework that allows reusable
components objects to communicate with one other & with the framework.
To start BDK
1. Change directory to c:\bdk1.1\beanbox
2. Execute batch file called run.bat
Beanbox will display four different windows
1. Toolbox- lists all beans registered for using it. Beans in toolbox are all
demo beans.
2. Beanbox/Main container window- is a central bean box window, because it
is the area where user lays out beans. Two menu items are file & edit.
Is a test container that enables user to layout, edit & interconnect
beans visually. In this user can try out the beans while developing
them to test all aspects of beans, including visual property, editing
event writing & bound property management.
3. Properties bean box- is property sheet window, which lists the properties
associated with currently selected bean. User can change colors, name
etc.
4. Method tracer indicates stat of method tracing.
Three parts of Bean are
1. Laying out properties The internal state of a bean is reflected by beans
member variables. Properties are public member variables that are
accessible externally. All member variables are important to beans
functionality, because the properties enable user to query a bean for
information or to modify beans state from outside bean. The developer is
allowed to read or write properties through accessor methods.
2. Accessor methods- Public methods define in a bean that enable access to
value of a particular property. The methods responsible for reading bean
properties are known as getter methods. Methods for writing bean property
are known as setter method.

Naming conventions for methods


1. Accessor method that gets property must begin with get.
2. Method that sets property must begin with set
Ex- public void setColor(Color c)
public Color getColor()
Properties
1. Simple property- Consist of single value property, which includes all
building java data type, classes & interfaces.
2. Boolean property
3. Indexed- it is an array on simple property
Ex. public color[] getValue()
3. Events If beans internal state changes it is necessary to notify outside
party of change. To achieve this, beans support events. Beans send
notification to current listener that registers itself with a bean, which
receives them. The listener to get registered, java bean supports multicast
events, that is multiple event listeners are registered.
Ex. public void add <eventlistenertype> (<eventlistenertpye>obj) throws
TooManyListException
Built in components
1. Orange button- Buttons with default color orange.
2. Our Button subclass of java.awt.canvas that acts as a simple GUI button,
will fire actionPerformed event after clicking on it.
Properties- foreground, background, font & name etc.
3. Explicit Button- Subclass of OurButton adds a BeanInfo class to specify
beans behavior & icons. Supports less properties & events than our button.
Explicit button also indicates that it has some hidden state by using
Feature Descriptors attribute value mechanism i.e. hidden state to true.
4. EventMonitor- Allows user to monitor all events fired by a source bean.
5. JellyBean- Draws an oval & supports a bound property color.
6. Juggler- is a simple animation. User can start & stop the animation by
connecting the button push events on two ExplicitButtons to start & stop
juggling.
7. TickTock- Simple invisible bean.
8. Molecule- Displays a 3D representation of a molecule. User can rotate the
molecule.
9. JDBC select- contacts a target database at a specific URL & runs a SQL
query to display or access specific information from a target table.

Exampleimport java.awt.*; import java.io.*;


public class mybean extends Button implements Serializable
{
private Color beancolor=Color.red;
private String caption="Hello";
public mybean()
{
setSize (60,40);
setColor (beancolor);
setLabel (caption);
}
public void paint(Graphics g)
{
g.setColor (beancolor);
setLabel (caption);
}
public Color getColor()
{ return beancolor; }
public void setColor(Color newcolor)
{
beancolor=newcolor;
setBackground (beancolor);
repaint();
}
public String getCaption()
{ return caption; }
public void setCaption(String newc)
{
String oldc=caption;
caption=newc;
setLabel (caption);
}
}
To run this1. Compile java file- javac mybean.java
2. Create a manifest fie with extension .mf
Name: mybean.class
Java-Bean: True
3. In the command prompt, type the followingjar cfm mybean.jar mybean.mf mybean.class

4. Start the BeanBox, & using load jar option load mybean.jar file.
5. Toolbox now contains an additional entry mybean.
JavaBean Specification guidelines1. A zero argument constructor must be provided for the bean class.
2. The constructor must not throw Exceptions.
3. Every property must have either setter or getter methods, with unique
name.
4. A bean must support persistence, i.e it must be serializable. The data
members, which do not need to be serialized, must be marked as
transient.
JAR (Java Archive Files)
- JAR file allows you to efficiently deploy a set of classes & their
associated resources
The utility is capable of packaging and storing files in compressed
format.
- The packaging is useful for java Applets & Beans to locate & load the
resource files as & when required.
- Its browser independent archive file format.
- Capable of storing audio & image files as well as class files.
The jar program is executed from command linejar {ctx} {vfm0M} {jarFile} {manifestfile} file1 file2 file3
[ The file1 are the name of class files. ]
Options arec
t
x
v
f
m
0 (Zero)
M

Create a new archive.


List table of contents for archive
Extract the named or all files from archive
Generate a verbose output
Specify the archive file name
Include information from specified manifest file
Dont use compression
Dont create a manifest file for the entries.

Manifest File (extension .mf)


A developer must provide a manifest file to indicate which of the
components in JAR file are Java Beans.
Ex- the defination of JAR file with 2 gif & one class file. The last entry is a Bean
Name: slide1.gif
Name: slide2.gif
Name: show.class
Java-Bean: true
A manifest file may reference several .class files. If a class file is a bean, its entry
must be followed by line Java-Bean: true
BeanInfo interface
Defines several methods including
1. PropertyDescriptor[ ] getPropertyDescriptors()
2. EventSetDescriptor [ ] getEventSetDescriptors( )
3. MethodDescriptor [ ] getMethodDescriptors( )
Returns arrays of objects that provide information about properties, events &
methods of bean.
SimpleBeanInfo is a class that provides default implementation of BeanInfo
interface including above 3 methods.
Example of BeanInfo display all properties supported by BeanImport java.beans.*;
public class info extends SimpleBeanInfo
{
public PropertyDescriptor[ ] getPropertyDescriptors() ;
try
{
PropertyDescriptor r=new PropertyDescriptor(rect, newcolors.class);
PropertyDescriptor pd[ ] = {rect};
return pd;
}
catch(Exception e) { }
return null;
}

Enterprise Java Beans (EJB)


- Based on component architecture
A set of interfaces between application servers & components is called
agreement. This will enable any component to run within any application server.
This will allow components to be switched in & out of various applications.
Servers without having to change code or recompiling the code, such an
agreement is also called Component Architecture.
- EJB standard is component architecture for deployable server-side components
in java.
- EJB components can be imported & loaded into an application server, which
hosts those components.
- Portability is easier & faster application construction is possible.
EJB components must be written in Java because1. It gives interface or implementation separation to ship components. This is
possible with interface & class keywords.
2. More safe & secure
3. Java runs on any platform.
EJB components can perform any of the following tasks1. Perform business logic- examples include computing the taxes on the
shopping cart, ensuring that manager has authority to approve the
purchase order or sending an order confirmation e-mail.
2. Access a database- Submitting an order for books, transferring money
between two bank a/cs.
3. Access another system.
Difference between EJB & GUI componentsGUI components are suited to handle client-side operations. EJB are server side
components & developed for performing server-side operation like executing
complex algorithms or performing high volume business transactions. These
components need to run in a highly available, fault-tole rant, transactional &
multi-user secure environment.
Client of EJB may be a Servlet, Applet or another enterprise beans also.
Types of EJBs
1. Session beans- Exists for single session.
- Session beans can be transactional, but are not recoverable following a
system crash.
- can be used for access database, adding numbers calling any other
enterprise beans.
2 types of session beans are
1. Stateless- these beans dont have internal state.
2. Stateful- Posses internal states.
2. Entity Beans- Entity beans models business data.

- They are data objects i.e. java objects that cache database information.
Ex.- a product, an order, an employee etc.
- These beans are transactional & survive from server crashes.
3. Message Driven beans- Same like session beans.
- You can call message-driven beans only by sending messages to those
beans.
Difference between EJB and Java Beans.
JavaBeans
----------------Basically used to CUSTOMIZE EXISTING OBJECTS. i.e. You can create USER
OBJECTS, which are based on existing objects.
Ex.: A default button operates as a Single-State Switch. i.e. when you press a
button on a web page, it doesn't remain pressed. Infact, it immediately bounces
back to its OFF state like a Door-Bell. Now, let's say, you need a button, which
should have 2 stable
states, like the typical Electrical Light Switch. So, in this case, what you can do is,
take an existing button (having 1 stable state) and CUSTOMIZE it so that it has 2
stable states. This is possible using JavaBeans.
Java Bean is a software component written in the Java programming
language that conforms to the JavaBeans component specification. The
JavaBeans APIs became part of the "core" Java APIs as of the 1.1 release of the
JDK.
The JavaBeans specification defines a Java-based software component
model that adds a number of features to the Java programming language. Some
of these features include: introspection , customization , events , properties ,
persistence
Enterprise Java Beans (EJB)
--------------------------EJB is a completely different concept than the one mentioned above. It is NOT
used to customize existing objects. Instead they are basically used to
STANDARDIZE the way, in which business logic is written.
Ex.: We can write our business logic as well as the GUI logic, inside
Servlets/Applets/StandAlone applications itself. But this way, there will be no
clear distinction between the Code that is responsible for the GUI and the actual
Business logic code, because everything is written inside the same class file.
So, to COMPONENTIZE we write business logic in separate class files
than the GUI logic, thereby making a clear distinction between the
responsibilities.
Enterprise JavaBeans (EJBs) are Java-based software components that
are built to comply with Java's EJB specification and run inside of an EJB

container supplied by a J2EE provider. An EJB container provides distributed


application functionality such as transaction support, persistence and lifecycle
management for the EJBs.
Difference between Session & Entity Beans
Session Bean

Entity Bean

The data members of the session bean


contain conversational state.

The data members of the entity bean


represent actual data in the domain
model.

A session bean may handle database


access for a single client.

Entity beans share database access for


multiple clients.

Because session beans are about a


conversation with a single client,
session beans are allowed to store perclient state information..

Because entity beans are shared


between multiple clients, they do not
allow storage of per-client state
information.

The relationship between a session


bean and its client is one-to-one.

The relationship between an entity


bean and a row in the domain model is
one-to-one.

The life of the session bean is limited to An entity bean persists as long as the
the life of its client.
data exists in the database.
Session beans can be transaction
aware.

Entity beans are transactional.

Session beans do not survive server


crashes.

Entity beans survive server crashes.

Example1. Deploying java bean in an application


// Source code for Area bean.
import java.awt.*; import java.io.Serializable;
public class Area extends Canvas implements Serializable
{
private Color color=Color.cyan;
public Area()
{
setSize(60,40);
setColor(color); }
public void paint(Graphics g)
{
g.setColor(color); }
public Color getColor()
{
return color;
}
public void setColor(Color newc)
{ color=newc;
setBackground (color); repaint(); }
}
// prg. for deploying bean.
import java.beans.*; import java.awt.*; import java.awt.event.*;
public class AreaApp
{
public AreaApp()
{
Frame f=new Frame ("Area Bean");
String name="Area"; f.setSize (300,300);
f.addWindowListener(new wa());
try
{
Area ab=(Area) Beans.instantiate (null, name);
f.setLayout (new FlowLayout());
f.add (ab); f.setVisible (true);
ab.setColor (Color.gray);
} catch(Exception e) { }
}
class wa extends WindowAdapter
{
public void windowClosing (WindowEvent we)
{
System.exit(0); }
}
public static void main(String args[])
{ new AreaApp(); }
}

EJB Architecture

EJB Server

EJB
Home
Client

EJB
Object

Container

Existing
System
s

EJB
Component

Database

EJB Server
The EJB Server is a collection of services for supporting an EJB installation
These services include management of distributed transactions, management
of distributed objects and distributed invocations on these objects, and low-level
system services
EJB Container
A container is a home for EJB components. EJB components live in a
container just as a record lives in a database
The container handles the EJBean lifecycle, including creating and destroying
an object
It provides a scalable, secure, transactional environment in which EJBeans can
operate
It handles state management of EJBeans
Container
The container provides an implementation of the EJBHome interface and an
implementation of the EJBObject remote interface
The container is also responsible for making the EJBHome interface available in
JNDI
EJB types
Session Beans
represent a transient conversation with a client and may or may not execute
database reads and writes
a session can be brief (as in a whois lookup) or can last a long time (as in a
large ftp download)
may invoke JDBC calls directly or may use Entity Beans to make the calls
acting as a client to the Entity Bean

store the state of the conversation but are transient


are destroyed if the server or client crashes
typically connect one-on-one with a single client
Entity Beans
represent data in a database and the methods to act on that data
are transactional and persistent
survive server or client crashes
share access with multiple clients (as in e-mail servers, database servers or
multi-player game servers)

You might also like