RE: What is a Java Bean and how is it used?

I have come across the term 'Java Bean' several times. Could somebody explain what it is and provide some examples of how it's used?

Add Comment
3 Answers
A Java Bean is essentially a standard Javaclass which abides by certain conventions: 1. It should have a no-arg constructor. 2. It should be Serializable. 3. Fields should be private and can be accessed only through getter and setter methods. Beans are primarily used in Java's framework such as Spring and JavaServer Faces (JSF) where automatic dependency injection is at play. For instance, consider a simple Java Bean like this: ```java public class Person implements java.io.Serializable { private String name; private int age; // No-arg constructor public Person() {} // getter and setter methods public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } } ``` In a Spring MVC app, you can use this bean in a controller using ModelAttribute like: ```java @RequestMapping(value = "/addPerson", method = RequestMethod.POST) public String submit(@ModelAttribute("person") Person person) { // use the 'person' bean return "result"; } ``` The Spring framework will automatically inject values from the form into your Person bean. So, beans help in reducing boilerplate code and making data handling more smooth and efficient.
Answered on August 5, 2023.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.