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

retrieve Bean programmatically

@Configuration public class MyConfig { @Bean(name = "myObj") public MyObj getMyObj() { return new MyObj(); } } I have this MyConfig object with @Configuration Spring annotation. My question is that how I can retrieve the bean…
user800799
  • 2,883
  • 7
  • 31
  • 36
20
votes
5 answers

Default method in interface in Java 8 and Bean Info Introspector

I have a little problem with default methods in Interface and BeanInfo Introspector. In this example, there is interface: Interface public static interface Interface { default public String getLetter() { return "A"; } } and two…
ptrr
  • 203
  • 1
  • 5
20
votes
4 answers

Could not autowire. No beans of SimpMessagingTemplate type found

I am configuring Websockets in Spring basically by following the guide provided in the documentation. I am currently trying to send a message from the server to the client as explained in the section "Sending messages from anywhere" Following the…
Tk421
  • 6,196
  • 6
  • 38
  • 47
20
votes
2 answers

SimpleStringProperty set() vs. setValue()

What is the difference between set(String) and setValue(String) in the SimpleStringProperty class? I know that set(String) is derived from StringPropertyBase, but this makes me even more wonder, why there additionally is setValue(String)?
stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270
20
votes
5 answers

ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/mail/MessagingException

I am getting a strange ClassFormatError when using the javaMail api to send email on my spring mvc web app. Below is my mail-cfg.xml
Jono
  • 17,341
  • 48
  • 135
  • 217
19
votes
2 answers

Why Java Beans have to be serializable?

Is it necessary that a Java Bean implements the Serializable interface?
Moritz
  • 199
  • 1
  • 1
  • 7
19
votes
2 answers

Java Spring Recreate specific Bean

I want to re-create (new Object) a specific bean at Runtime (no restarting the server) upon some DB changes. This is how it looks - @Component public class TestClass { @Autowired private MyShop myShop; //to be refreshed at runtime bean …
Srikar Appalaraju
  • 71,928
  • 54
  • 216
  • 264
19
votes
4 answers

java listen to ContextRefreshedEvent

I have a classX in my spring application in which I want to be able to find out if all spring beans have been initialized. To do this, I am trying to listen ContextRefreshedEvent. So far I have the following code but I am not sure if this is…
kk1957
  • 8,246
  • 10
  • 41
  • 63
18
votes
6 answers

What's the point of beans?

I've bean doing some JSP tutorials and I don't understand what the point of a bean class is. All it is, is get and set methods. why do we use them? public class UserData { String username; String email; int age; public void setUsername( String…
brblol
  • 189
  • 1
  • 4
18
votes
1 answer

Spring-boot gets an error when creating custom RestTemplate

I have a sendGetREST method to send some URL endpoint and get the response: @Component public class HttpURLCommand { private static Logger logger = Logger.getLogger(HttpURLCommand.class); public String sendGetREST(String soapUrl, Object[]…
Shofwan
  • 451
  • 2
  • 6
  • 16
18
votes
5 answers

Java Beans: What am I missing?

I'm wondering if I'm missing something about Java Beans. I like my objects to do as much initialization in the constructor as possible and have a minimum number of mutators. Beans seem to go directly against this and generally feel clunky. What…
Dave Ray
  • 39,616
  • 7
  • 83
  • 82
18
votes
3 answers

Spring/Eclipse 'referenced bean not found' warning when using ?

I have just broken up a Spring bean configuration file into smaller external files and have used the the "import" directive to include them in my Spring Test application context XML file. But whenever I reference one of the beans from the imported…
Dave
  • 21,524
  • 28
  • 141
  • 221
18
votes
4 answers

What are JavaBeans in plain English?

Before I start I would just like everyone know that I did indeed spend a good time googling this and found a lot of explanations and definitions. But even so after spending hours reading the subject still seems rather vague. I know I have to ask…
user818700
17
votes
3 answers

BeanUtils.copyProperties convert Integer null to 0

I noticed that BeanUtils.copyProperties(dest, src) has a strange side effect. All null Integers (probably Long, Date etc. too) convert to 0 in both objects: source (sic!) and destination. Version: commons-beanutils-1.7.0 javadoc: Copy property…
lukastymo
  • 26,145
  • 14
  • 53
  • 66
17
votes
1 answer

Get bean property getter or setter by reflection?

Suppose I have a handle on an object of type , and I'm told by configuration that it has a bean property of type int with the name age. How can I retrieve the getter for this document? Is there a better way than prepending "get" and capitalizing…
C. Ross
  • 31,137
  • 42
  • 147
  • 238