tags:

views:

287

answers:

3

Hi ,

What is a java bean ..why do i need it .since i can solve all apps with my class and interface structure. Why do i need beans.And can you point me a place where beans are essential instead of class and interface?

Please explain the essentiality of a bean in the below context:

  • Wep apps

  • Standalone Apps

+5  A: 

Beans themselves

JavaBeans are everywhere, they're a convention and just about every single slightly larger library out there uses those conventions to automate things. Just a few reasons why JavaBeans should be used:

  • They serialize nicely.
  • Can be instantiated using reflection.
  • Can otherwise be controlled using reflection very easily.
  • Good for encapsulating actual data from business code.
  • Common conventions mean anyone can use your beans AND YOU CAN USE EVERYONE ELSE'S BEANS without any kind of documentation/manual easily and in consistent manner.
  • Very close to POJOs which actually means even more interoperability between distinct parts of the system.

Also there's of course Enterprise JavaBeans which are a whole another matter and shouldn't be mixed with plain JavaBeans. I just wanted to mention EJB:s because the names are similar and it's easy to get those two confused.

Beans in web applications

If you consider "normal" JavaBeans in web app context, they make more sense than wearing shoes in your legs. Since the Servlet specification requires for sessions to be serializable, it means you should store your data in session as something that's serializable - why not make it a bean then! Just throw your SomeBusinessDataBean into the session and you're good to go, laughably easy, specification-compliant and convenient.

Also transferring that data around the application is easy too since JavaBeans help you to decouple parts of your application completely. Think JavaBeans as a letter and various subsystems of the application as departments within a very large corporation: Dept.A mails a bunch of data to Dept.B, Dept.B doesn't know -or even care- where the data came from just as it should be and can just open the letter, read stuff from it and do its thing based on that data.

Beans in standalone applications

Actually what's above applies to standalone apps too, the only difference is that you can mess up with the UI a bit more since standalone applications have stateful UI:s while web applications have statelss UI:s which in some cases only simulate stateful UI:s. Because of this different it's easier to make a mess with standalone application but that's worth a whole another topic and isn't directly related to JavaBeans at all.

Esko
+3  A: 

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 Integer age;

    // Getters.
    public Long getId() { return id; }
    public String getName() { return name; }
    public Integer getAge() { return age; }

    // Setters.
    public void setId(Long id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setAge(Integer age) { this.age = age; }

    // 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,age=%d]", id, name, age);
    }
}

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.setAge(resultSet.getInteger("age"));
    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>Age</th>
    </tr>
    <c:forEach items="${users}" var="user">
        <tr>
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.age}</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:

BalusC
+1  A: 

A bean is nothing much, really. For a class to be a "bean", all it requires is:

  • to have a public, no argument constructor
  • to be serializable (to implement the Serializable interface, either directly or through one of its super classes).

To that, you can add getters and setters for properties of the class that conform to a specific naming convention if you want the fields to be discoverable in certain circumstances (e.g. making that class some object you can drag and drop from a visual editor in your IDE, for example).

You can find more directly from Sun here.

JRL