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
10
votes
4 answers

redirect from jsf?

I am working on application with jsp, jstl and jsf for my college project, thats being said, I am as well very new to jsf. Everything is going great so far. However, I seems to have a problem figuring out how to do redirect from managed bean to page…
Dmitris
  • 3,408
  • 5
  • 35
  • 41
10
votes
3 answers

Should I add support for PropertyChangeSupport and PropertyChangeListener in a Java bean for a web application?

I noticed that some people write beans with support for the Property Change observer pattern. import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; public class SampleBean implements…
James McMahon
  • 48,506
  • 64
  • 207
  • 283
10
votes
6 answers

Common algorithm for generating a diff of the fields in two beans?

Let's say you have two instances of the same bean type, and you'd like to display a summary of what has changed between the two instances - for example, you have a bean representing a user's settings in your application, and you'd like to be able to…
matt b
  • 138,234
  • 66
  • 282
  • 345
10
votes
1 answer

Understanding Spring context initialization order

I have a complex set of beans and dependencies between them. All beans are @Service, @Repository or @Controller annotated and I use the @PostConstruct annotation. There are some circular dependencies but still the system was correctly initialized by…
Jan
  • 2,803
  • 6
  • 36
  • 57
10
votes
1 answer

Spring Boot Convention for Variables

So I have an application.yml file for my spring boot application like so: spring: url: localhost email: from: something@gmail.com app: uuid: 3848348j34jk2dne9 I want to wire these configuration properties into different components in my app…
Richard
  • 5,840
  • 36
  • 123
  • 208
10
votes
4 answers

Disable JMS consuming bean in unit-test

I've build a Spring application that receives JMS messages (@JmsListener). During development I'd like to send some messages to the JMS-queue the listener listens to, so I wrote a unit-test that sends some messages (JmsTemplate). In this unit-test I…
codesmith
  • 1,381
  • 3
  • 20
  • 42
10
votes
2 answers

JavaBeans Comparison

Does anyone know about a free open source library (utility class) which allows you to compare two instances of one Java bean and return a list/array of properties which values are different in those two instances? Please post a small…
Tomas
10
votes
3 answers

Spring bean fields injection

Using Spring IoC allows to set bean properties exposed via setters: public class Bean { private String value; public void setValue(String value) { this.value = value; } } And the bean definition is:
Vladimir
  • 9,913
  • 4
  • 26
  • 37
10
votes
1 answer

Accessing a JSF managedBean from a Servlet

I need to know what's the best method for accessing a JSF managedBean (which is defined having application scope) from a servlet. Currently I have something like this in my servlet: MyApplicationScopeBean bean = null; try { FacesContext…
azathoth
  • 573
  • 2
  • 6
  • 18
10
votes
2 answers

Java Introspection - weird behaviour

The code below is a small example that easily reproduces the issue. So I have variable of type String, on which a default value is set. I have 3 methods: getter setter convenience method that converts the string to boolean The introspection does…
Quirexx
  • 173
  • 3
  • 15
10
votes
6 answers

Are Java Beans as data storage classes bad design?

Usually JavaPractices.com is a good site with good idea's, but this one troubles me: JavaBeans are bad. The article cites several reasons, mainly that the term JavaBean means "A Java Bean is a reusable software component that can be manipulated…
TheLQ
  • 14,830
  • 14
  • 69
  • 107
10
votes
4 answers

Copy properties from one bean to another (not the same class) recursively (including nested beans)

Which approach requires the least amount of own written code to achieve a deep copy of one bean to another? The goal is to do it in an automatic way when source and target properties are matched by name. source main bean: public class SourceBean { …
S. Pauk
  • 5,208
  • 4
  • 31
  • 41
10
votes
1 answer

PMD "Bean Members Should Serialize" rule. Can we do it in more smart way?

Here is (probably good for someone) "Bean Members Should Serialize" PMD rule which states the following: If a class is a bean, or is referenced by a bean directly or indirectly it needs to be serializable. Member variables need to be marked as…
Roman Nikitchenko
  • 12,800
  • 7
  • 74
  • 110
10
votes
3 answers

Can't map a Query String parameters to my JavaBean (using Spring 4 and Datatables)

I'm really stuck into trying to map my QueryString parameters into my Spring JavaBean Command object here, and I couldn't find an answer to my question so far. I'm using jQuery Datatables plugin with server side processing so that each action in my…
Berger
  • 306
  • 2
  • 10
10
votes
1 answer

How to check if bean property exist win BeanUtils or similar?

Is there ready made routine to check if bean has getter for specific property name given by string?
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385