What Is a Javabean Exactly

What is a JavaBean exactly?

A JavaBean is just a standard. It is a regular Java class, except it follows certain conventions:

  1. All properties are private (use getters/setters)
  2. A public no-argument constructor
  3. Implements Serializable.

That's it. It's just a convention. Lots of libraries depend on it though.

With respect to Serializable, from the API documentation:

Serializability of a class is enabled by the class implementing the
java.io.Serializable interface. Classes that do not implement this
interface will not have any of their state serialized or deserialized.
All subtypes of a serializable class are themselves serializable. The
serialization interface has no methods or fields and serves only to
identify the semantics of being serializable.

In other words, serializable objects can be written to streams, and hence files, object databases, anything really.

Also, there is no syntactic difference between a JavaBean and another class -- a class is a JavaBean if it follows the standards.

There is a term for it, because the standard allows libraries to programmatically do things with class instances you define in a predefined way. For example, if a library wants to stream any object you pass into it, it knows it can because your object is serializable (assuming the library requires your objects be proper JavaBeans).

What is a Java Bean?

Any serializable java class (implementing java.io.Serializable) that follows specific conventions: a no-argument constructor, and properties accessible via get/set/is accessors.

The idea is to make it predictable, so that properties etc can be discovered automatically through reflection - of great help in tool and framework development.

What are JavaBeans in plain English?

A javabean is a standard. All Javabeans have the following 3 qualities:

1) The class implements Serializable

2) All fields have public setters and getters to control access.

3) A public no-argument constructor.

Difference between JavaBean and Spring bean

JavaBeans:

At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. Specifically, classes that

  • have public default (no argument) constructors
  • allow access to their properties using accessor (getter and setter) methods
  • implement java.io.Serializable

Spring Beans:

A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in Spring configuration files (or, more recently, with annotations), instantiated by Spring containers, and then injected into applications.

Note that Spring beans need not always be JavaBeans. Spring beans might not implement the java.io.Serializable interface, can have arguments in their constructors, etc.

This is the very basic difference between JavaBeans and Spring beans.

For more information, refer to the source of the above text, Shaun Abram's article JavaBeans vs Spring beans vs POJOs.

Beans in java programming

That depends.

You could be talking about Spring beans, Enterprise Java Beans or some other variant.

The general answer is that beans are some type of generic object (or POJO perhaps) that hold information - almost think of them like their own data type. The distinction is that they typically don't have much in the way of behaviors eg, they only have: simple fields, getters, setters.

Difference between Bean, Java Bean and Enterprise Java Beans

The plain term "bean" is frequently used as as a shortcut to JavaBean or Enterprise Java Bean (depending on the context). So, the term exists in the common language of programmers and it refers in general to reusable objects/components in Java.

JavaBean is a POJO class with specific naming conventions for getters and setters, true and not only that: it is usually an encapsulation of other objects (properties), is serialisable and with a zero-argument constructor.
There is a complete specification developed by Sun (at that moment) about JavaBean. Sun defined it as "a reusable software component that can be manipulated visually in a builder tool". Moreover, in JavaBean Specification it is stated that:

Individual Java Beans will vary in the functionality they support, but the typical unifying features that distinguish a Java Bean are:

  • Support for “introspection” so that a builder tool can analyze how a bean works
  • Support for “customization” so that when using an application builder a user can customize the appearance and behaviour of a bean
  • Support for “events” as a simple communication metaphor than can be used to connect up beans
  • Support for “properties”, both for customization and for programmatic use.
  • Support for persistence,so that a bean can be customized in an application
    builder and then have its customized state saved away and reloaded
    later.

The essential part is that can be visually manipulates hence the need for getters/setters, events, zero-argument constructor (so that they can be externally instantiated), serialisable.

Check this link for more details: http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf?AuthParam=1435694253_b87821c280430a0230bf8d22223c79d2

What is the difference between a JavaBean and a POJO?

A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serialisable etc. See JavaBeans Conventions for more details.

A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.

What is a good use case of Java Beans?

A number of libraries and specifications (e.g. JPA, JavaEL) use the Java Beans spec and rely on exactly that behavior.

Using getters and setters has the advantage of letting you add code inside those methods, e.g. to create "virtual" properties which are calculated at runtime rather than stored in a field.

Additionally using getters and setters allows other frameworks to wrap those methods and provide additional functionality like change logging etc. In many cases this is done by internally creating a subclass and overriding the getters and setters. The user would not notice that since that "weaving" or "proxying" is often done at runtime. Hibernate for example uses this to provide lazy loading functionality when you call a getter to access a related collection or entity.

Update:

As per request an example for "virtual" properties:

Assume you have a Person bean which has the fields firstName and lastName. You could add a read-only virtual property name by providing the following getter:

public String getName() {
return getFirstName() + " " + getLastName();
}

Update 2:

Another note on why getters and setters are necessary: this basically comes from how Java works. Languages that directly support properties, like C#, would allow you to write code like person.firstName = "Joe"; and still use a setter if there is one or throw an error if the property is read-only. So if you'd add a setter for firstName those languages would internally translate firstName = "Joe" to setFirstName("Joe") without the developer having to change anything - quite an elegant solution. :)

Since Java doesn't support that, we have to always provide accessor methods (setters/getters) even if they don't do anything special - just in case they might need to be changed in the future.

Places where JavaBeans are used?

They often just represents real world data. Here's a simple example of a Javabean:

public class User implements java.io.Serializable {

// Properties.
private Long id;
private String name;
private Date birthdate;

// Getters.
public Long getId() { return id; }
public String getName() { return name; }
public Date getBirthdate() { return birthdate; }

// Setters.
public void setId(Long id) { this.id = id; }
public void setName(String name) { this.name = name; }
public void setBirthdate(Date birthdate) { this.birthdate = birthdate; }

// Important java.lang.Object overrides.
public boolean equals(Object other) {
return (other instanceof User) && (id != null) ? id.equals(((User) other).id) : (other == this);
}
public int hashCode() {
return (id != null) ? (getClass().hashCode() + id.hashCode()) : super.hashCode();
}
public String toString() {
return String.format("User[id=%d,name=%s,birthdate=%d]", id, name, birthdate);
}
}

Implementing Serializable is not per se mandatory, but very useful if you'd like to be able to persist or transfer Javabeans outside Java's memory, e.g. in harddisk or over network.

In for example a DAO class you can use it to create a list of users wherein you store the data of the user table in the database:

List<User> users = new ArrayList<User>();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getLong("id"));
user.setName(resultSet.getString("name"));
user.setBirthdate(resultSet.getDate("birthdate"));
users.add(user);
}
return users;

In for example a Servlet class you can use it to transfer data from the database to the UI:

protected void doGet(HttpServletRequest request, HttpServletResponse response) {
List<User> users = userDAO.list();
request.setAttribute("users", users);
request.getRequestDispatcher("users.jsp").forward(request, response);
}

In for example a JSP page you can access it by EL, which follows the Javabean conventions, to display the data:

<table>
<tr>
<th>ID</th>
<th>Name</th>
<th>Birthdate</th>
</tr>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td><c:out value="${user.name}" /></td>
<td><fmt:formatDate value="${user.birthdate}" pattern="yyyy-MM-dd" /></td>
</tr>
</c:forEach>
</table>

Does it make sense? You see, it's kind of a convention which you can use everywhere to store, transfer and access data.

See also:

  • JavaBeans specification


Related Topics



Leave a reply



Submit