Spring Beans
BEAN ek object hai jo Spring IoC container KE DWARA create, configure, aur manage kiya jaata hai. Har bean ki apni ID/name hoti hai container mein. Beans DEFINE ki teen tareeke se ho sakti hain: XML configuration (purana), Java-based @Configuration + @Bean methods, ya ANNOTATION-based (@Component, @Service, @Repository, @Controller — sab @Component ke specialized versions).
Default mein, Spring beans SINGLETON hote hain — poore application context mein SIRF EK instance banti hai, sab jagah SAME instance share hoti hai. Ye stateless services ke liye perfect hai (jaise OrderService) — memory efficient, aur thread-safe (agar service khud stateless ho).
// Annotation-based bean (most common):
@Service
public class EmailService {
public void send(String to, String msg) { /* ... */ }
}
// Java-config based bean (jab third-party class ko bean banana ho):
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
// Usage — container se automatically injected:
@Service
public class NotificationService {
private final EmailService emailService; // Spring inject karega
public NotificationService(EmailService emailService) {
this.emailService = emailService;
}
}- Bean = container-managed object, unique ID ke saath
- Default scope = SINGLETON (ek hi instance, poore app mein share)
- @Component family (@Service, @Repository, @Controller) ya @Bean methods se define hoti hain
Singleton ke alawa, Spring mein aur bhi scopes hain — PROTOTYPE (har getBean() call par NAYI instance), REQUEST (web app mein, ek HTTP request ke liye ek instance), SESSION (ek user session ke liye ek instance). @Scope("prototype") annotation se change kar sakte ho.
@Component
@Scope("prototype")
public class ShoppingCart {
// Har user ke liye ALAG instance chahiye — prototype scope
}Default mein, bean ka NAME class name hota hai (camelCase mein — jaise EmailService → "emailService"). @Component("customName") se explicitly bean ka naam SET kar sakte ho — useful jab MULTIPLE implementations ek hi interface ki hon, aur specific ek CHOOSE karni ho @Qualifier ke saath.
- Default bean name = class name, camelCase mein
- @Component("myBean") = custom naam
- Useful jab multiple implementations exist karte hon