IoC Container
IoC Container Spring ka HEART hai — objects (beans) ko CREATE, CONFIGURE, aur MANAGE karta hai, poori application lifecycle ke through. Normally, object apni dependencies KHUD create karta hai (control uske paas). IoC mein, ye control INVERT ho jaata hai — container dependencies create karke object ko DETA hai.
Do main container types hain: BeanFactory (basic, lazy initialization) aur ApplicationContext (advanced, ZYAADA features — event handling, internationalization, AOP integration; EAGER initialization by default). Practically, ApplicationContext hi almost hamesha use hota hai — BeanFactory sirf memory-constrained environments ke liye.
// ApplicationContext — Spring ka main container:
ApplicationContext context =
new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
// Container ne UserService, aur uski saari dependencies, khud create ki
// Spring Boot mein, ye automatically hota hai:
@SpringBootApplication
public class MyApp {
public static void main(String[] args) {
SpringApplication.run(MyApp.class, args); // container internally banta hai
}
}- IoC Container = objects create/configure/manage karta hai
- ApplicationContext = modern, feature-rich container (almost always use hota hai)
- Control INVERTED — object apni dependencies khud nahi banata
BeanFactory LAZY hai — beans TABHI create hoti hain jab getBean() call ho. ApplicationContext EAGER hai (default) — application startup ke waqt hi SAARI singleton beans create ho jaati hain. Isse startup thoda slow hota hai, lekin runtime errors JALDI pakde jaate hain (agar koi bean configuration galat hai, app START HI NAHI hoga).
ApplicationContext ke DIFFERENT implementations hain based on kaha se configuration aa rahi hai — AnnotationConfigApplicationContext (Java-based @Configuration classes se), ClassPathXmlApplicationContext (XML files se, legacy), aur Spring Boot mein automatically ConfigurableApplicationContext bana leta hai (embedded web server ke saath).
- AnnotationConfigApplicationContext = Java @Configuration classes
- ClassPathXmlApplicationContext = legacy XML config
- Spring Boot = automatically configured, embedded server support ke saath