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
5 answers

Is a boolean property name prefixed by "is" still a valid Java Bean?

I just noticed something I didn't know. private boolean isCertified; public boolean isCertified() { return isCertified; } public void setCertified(boolean certified) { isCertified = certified; } The following getters and setters…
Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
10
votes
1 answer

What is difference between JavaBean and ManagedBean

I am reading What components are MVC in JSF MVC framework? In the big architectural picture, your own JSF code is the V: M - Business domain/Service layer (e.g. EJB/JPA/DAO) V - Your JSF code C - FacesServlet In the developer picture, the…
Jeff Lee
  • 783
  • 9
  • 17
10
votes
4 answers

Reading a dynamic property map into Spring managed bean

I have a properties file like this: my.properties file: app.One.id=1 app.One.val=60 app.Two.id=5 app.Two.val=75 And I read these values into a map property in my bean in Spring config file like this: spring-config.xml:
kriver
  • 1,588
  • 3
  • 20
  • 33
10
votes
6 answers

How important are naming conventions for getters in Java?

I’m a huge believer in consistency, and hence conventions. However, I’m currently developing a framework in Java where these conventions (specifically the get/set prefix convention) seem to get in the way of readability. For example, some classes…
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
10
votes
4 answers

How to print Java Bean completely using reflection or any other utility

I have an Java bean class Person containing 3 variables: name (String) age (String) address (Object). Address contains 3 variables: street door_no city I would like to have a utility which should print all variables in Person. By this I mean…
sridhar
  • 1,117
  • 5
  • 31
  • 59
9
votes
3 answers

How to control order of bean init-method invocation in Spring?

Suppose I have bean, which init-method or constructor should be called after init-method of another bean. Is it possible?
Shikarn-O
  • 3,337
  • 7
  • 26
  • 27
9
votes
3 answers

Convert xml to java bean

How can I covert a an xml file to a simple java bean? Its a simple xml file without any xsd, which was generated from a java bean, which I don't have access to. I tried using xmlbeans to first generate the xmd from xml and then to generate classes…
outvir
  • 531
  • 4
  • 8
  • 11
9
votes
2 answers

JSF - Get the SessionScoped Bean instance

I have this configuration on my web application. 2 beans : 1° Bean - It checks the login; @ManagedBean(name="login") @SessionScoped public class Login { private String nickname; private String password; private boolean isLogged; …
markzzz
  • 47,390
  • 120
  • 299
  • 507
9
votes
2 answers

How to replace an existing bean in spring boot application?

I spring boot application, There already an bean creation in one auto configuraton class from a dependent jar like bellow: @Bean @Order(100) public StaticRouteLocator staticRouteLocator(AdminServerProperties admin) { Collection routes…
leo
  • 583
  • 2
  • 7
  • 20
9
votes
5 answers

Copy non-null properties from one object to another using BeanUtils or similar

my aim is to copy fields of one object into another, but only those that aren't null. I don't want to assign it explicitly. A more generic solution would be very useful and easier to maintain i.e. for implementing PATCH in REST API where you allow…
kiedysktos
  • 3,910
  • 7
  • 31
  • 40
9
votes
1 answer

How can I specify a custom MANIFEST.MF file while using the Maven Shade plugin?

When a project uses the Maven-jar-plugin, it's easy to include a custom manifest file in the jar, but I can't find a way to do the same thing with Maven shade. How can I use my own manifest file while using the "Maven-shade-plugin"? Additional…
BlakeTNC
  • 941
  • 11
  • 14
9
votes
1 answer

How to get value of bean property when property name itself is a dynamic variable

I'm trying to write a custom JSPX tag that reads the value of a given bean property from each object in a given list, with the name of that property passed to the tag as a JSP attribute. The tag would look something like this:
Andrew Swan
  • 13,427
  • 22
  • 69
  • 98
9
votes
2 answers

Spring Core Framework - Where are the beans hold?

I am a junior Java developer and I am reading the spring documentation from spring.io. I read that every bean that gets registered in the *.xml file that spring uses to resolve dependencies is declared using tags. My question is: In…
9
votes
1 answer

Is it a good idea to always use the Java Beans naming conventions?

I have always found it very useful to adhere to the Java Beans naming conventions: getX(), setX(), isX(), etc. I think the Java Bean naming conventions provide several main advantages: When looking through code, you can immediately determine the…
user3144349
  • 419
  • 1
  • 4
  • 12