Tuesday, 31 December 2024

ava Bean

 

✅ 1. What is a Java Bean (Simplified)

Think of a Java Bean like a container to hold data — for example: name, email, age, etc.

๐ŸŽฏ Rules for Java Bean:

  1. It should have private variables

  2. It should have public getters and setters

  3. It should have a no-argument constructor


๐Ÿ”ง Example: Customer Java Bean

java
public class Customer { private String name; // private variable private int age; // No-argument constructor public Customer() {} // Getter public String getName() { return name; } // Setter public void setName(String name) { this.name = name; } // Getter public int getAge() { return age; } // Setter public void setAge(int age) { this.age = age; } }

๐Ÿ’ก How do you use this Java Bean?

You can create an object and set/get values using the setters and getters:

java
Customer customer = new Customer(); customer.setName("Mitesh"); customer.setAge(30); System.out.println(customer.getName()); // Output: Mitesh System.out.println(customer.getAge()); // Output: 30

✅ 2. What is a Spring Bean?

A Spring Bean is just a Java object that is created and managed by the Spring Framework.

Spring takes care of:

  • Creating the object

  • Injecting dependencies

  • Managing the lifecycle


๐Ÿงช Real Example with Spring Boot

๐Ÿ“ฆ Step 1: Create a simple class

java
@Component // Tells Spring to manage this class as a bean public class HelloService { public String sayHello() { return "Hello from Spring Bean!"; } }

๐Ÿš€ Step 2: Use this bean in another class

java
@RestController public class HelloController { private final HelloService helloService; // Spring injects HelloService automatically (this is called Dependency Injection) public HelloController(HelloService helloService) { this.helloService = helloService; } @GetMapping("/hello") public String hello() { return helloService.sayHello(); } }

๐Ÿ“Œ Now, when you run the Spring Boot app and open http://localhost:8080/hello, it shows:

csharp
Hello from Spring Bean!

๐Ÿง  Summary

ConceptPurposeExample
Java BeanHolds data (like a data model)Customer with get/set
Spring BeanObject created and managed by Spring FrameworkHelloService, @Component

No comments:

Post a Comment