Questions tagged [javabeans]

A javabean is a custom class which often represents real-world data and encapsulates private properties by public getter and setter methods. For example, User, Product, Order, etc.

Javabeans

A javabean is a custom class which often represents real-world data and encapsulates private properties by public getter and setter methods. For example, User, Product, Order, etc. In applications using a database, they are often 1:1 mapped to a database table. A single database row can then be represented by a single javabean instance.

Basic example

Here's an example of a javabean representing an User (some newlines are omitted for brevity):

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 mandatory, in order to be able to persist or transfer javabeans outside Java's memory; E.G. on a disk drive, a database, or over the network. In case of web applications, some servers will do that with HTTP sessions (e.g. save to disk before restart, or share with other servers in cluster). Any internal variables that do not have getters/setters should be marked transient to prevent them from being serialized.

Implementing toString() is not mandatory, but it is very useful if you'd like to be able to log/print the object to a logger/stdout and see a bit more detail than only com.example.User@1235678.

Implementing equals() and hashCode() is mandatory for the case you'd like to collect them in a Set or a HashMap, otherwise different instances of javabeans which actually contain/represent the same data would be treated as different representations.

Code generation

A bit sane IDE like Eclipse/IntelliJ/Netbeans can autogenerate all necessary constructors and methods based on only a bunch of fields. So you could just start off with only the necessary fields:

public class User implements java.io.Serializable {

    private Long id;
    private String name;
    private Date birthdate;

}

And then right click somewhere in the source code and choose Source and then you'll get a list of various useful Javabean-related options such as generating of getters/setters, hashCode()/equals() and toString().

enter image description here


Usage example - JDBC

In for example a JDBC database access object (DAO) class you can use it to create a list of users wherein you store the data of the User table in the database:

public List<User> list() throws SQLException {
    List<User> users = new ArrayList<User>();

    try (
        Connection connection = database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT id, name, birthdate FROM User");
        ResultSet resultSet = statement.executeQuery();
    ) {
        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;
}

Usage example - Servlet

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("/WEB-INF/users.jsp").forward(request, response);
}

Usage example - JSP

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>

(note: the <c:out> is just to prevent XSS holes while redisplaying user-controlled input as string)

Documentation

3994 questions
32
votes
6 answers

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I have results from Query query = session.createQuery("From Pool as p left join fetch p.poolQuestion as s"); query and I would like to display it on JSP. I have loop:
Ilkar
  • 2,113
  • 9
  • 45
  • 71
32
votes
4 answers

Spring @ConditionalOnProperty havingValue = "value1" or "value2"

I am looking for configurationOnProperty usage where I can specify to consider more than one value as shown below Eg: @ConditionalOnProperty(value = "test.configname", havingValue = "value1" or "value2") OR I would like to know if it is possible to…
MLS
  • 617
  • 1
  • 7
  • 14
32
votes
4 answers

View all fields / properties of bean in JSP / JSTL

I have a bean, ${product}. I would like to view all of the available fields / properties of this bean. So for instance, ${product.price}, ${product.name}, ${product.attributes.colour} etc. Is it possible to dynamically print out all names and…
Toby
  • 1,651
  • 2
  • 18
  • 31
31
votes
1 answer

Bean Validation Groups - Understanding it correctly

I am trying to understand the Groups in Bean validation. So for instance if I have a bean and I want only certain field validated for certain cases, I should group them? @NotNull (groups=MyClassX.class) @Min (groups=MyClassA.class) // 1 …
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173
31
votes
5 answers

How to pass parameters dynamically to Spring beans

I am new to Spring. This is the code for bean registration: and this is my bean class: public class User_Imple implements Master_interface { private int id; …
Ramesh J
  • 794
  • 2
  • 11
  • 24
29
votes
4 answers

Java Reflection Beans Property API

Is there any standard way to access Java Bean Property like class A { private String name; public void setName(String name){ this.name = name; } public String getName(){ return this.name; } } So can I access this…
Troydm
  • 2,642
  • 3
  • 24
  • 35
29
votes
1 answer

When method marked with @PostConstruct called?

At which phase of the JSF request processing lifecycle, the backing bean method marked with @PostConstruct called?
siva636
  • 16,109
  • 23
  • 97
  • 135
29
votes
4 answers

Why Java Beans are called "beans"?

I am a Java developer and I am working with Beans everyday. I am curious about the history of the name "Bean". Does it just comes from coffe bean, or is there something else?
Han
  • 592
  • 2
  • 6
  • 9
29
votes
5 answers

How does Spring bean Handle concurrency

My web application uses Spring IOC. So all my spring beans will be singletons by default. In case if two requests try to access two different methods of a single class (for example MySpringBean is a class which has two methods searchRecord and…
Rajeev Akotkar
  • 1,377
  • 4
  • 26
  • 46
28
votes
6 answers

Spring - set a property only if the value is not null

When using Spring, is it possible to set a property only if the value passed is not null? Example: The behavior I'm looking for is: some.Type myBean =…
RonK
  • 9,472
  • 8
  • 51
  • 87
27
votes
5 answers

reading a dynamic property list into a spring managed bean

I've been searching but cannot find these steps. I hope I'm missing something obvious. I have a properties file with the following contents: machines=A,B I have another file like that but having a different number of members in the machines element…
bob
  • 273
  • 1
  • 3
  • 4
27
votes
4 answers

Defining the same Spring bean twice with same name

Is having two definition for a bean (with same name and class) valid in Spring IOC ? I am having two bean definition files included in web.xml. See the sample below. applicationContext-beans1.xml
hop
  • 2,518
  • 11
  • 40
  • 56
26
votes
6 answers

when is a spring beans destroy-method called?

I have put a sysout statement in the "destroy-method" for a bean. When i run a sample code, the sysout is not getting output. Does that mean the destroy-method is not getting called ? The Test Class: package spring.test; import…
java_geek
  • 17,585
  • 30
  • 91
  • 113
26
votes
6 answers

What is the advantage of using Java Beans?

I believe I understand what Java Beans are: Java class(es) which contain a no-arg constructor, are serializable, and expose their fields with getters and setters. Does a Java Bean have to expose all of its fields in order to qualify as a bean? If…
Brian S
  • 4,878
  • 4
  • 27
  • 46
26
votes
5 answers

JavaBean equivalent in Python

I am fairly new to using Python as a OOP. I am coming from a Java background. How would you write a javabean equivalent in python? Basically, I need a class that: Implements serializable. Has getters and setters -> private properties dummy…
stealthspy
  • 659
  • 1
  • 6
  • 12