0
0
Spring Bootframework~5 mins

IoC container mental model in Spring Boot

Choose your learning style9 modes available
Introduction

The IoC container helps manage and create objects for your app automatically. It makes your code cleaner and easier to change.

When you want Spring Boot to create and manage your app's objects for you.
When you want to easily swap parts of your app without changing lots of code.
When you want to organize your app so objects can work together smoothly.
When you want to avoid writing code that manually creates and connects objects.
When you want to use features like automatic setup and configuration in Spring Boot.
Syntax
Spring Boot
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService service = context.getBean(MyService.class);

ApplicationContext is the main IoC container interface in Spring.

You ask the container for objects (beans) instead of creating them yourself.

Examples
This defines a bean named myService that the IoC container will manage.
Spring Boot
@Configuration
public class AppConfig {
    @Bean
    public MyService myService() {
        return new MyServiceImpl();
    }
}
Using @Component lets Spring automatically detect and manage this class as a bean.
Spring Boot
@Component
public class MyServiceImpl implements MyService {
    // service code here
}
This injects the MyService bean into another class automatically.
Spring Boot
@Autowired
private MyService myService;
Sample Program

This program shows how Spring's IoC container creates and gives you a GreetingService object automatically. You just ask the container for it.

Spring Boot
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.*;
import org.springframework.stereotype.Component;

interface GreetingService {
    String greet();
}

@Component
class HelloService implements GreetingService {
    public String greet() {
        return "Hello from IoC container!";
    }
}

@Configuration
@ComponentScan
class AppConfig {}

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        GreetingService service = context.getBean(GreetingService.class);
        System.out.println(service.greet());
    }
}
OutputSuccess
Important Notes

The IoC container uses @Component, @Configuration, and @Bean to know what to manage.

It helps keep your code simple by handling object creation and wiring behind the scenes.

Remember to enable component scanning with @ComponentScan so Spring finds your beans.

Summary

The IoC container manages your app's objects automatically.

You define beans and Spring creates and connects them for you.

This makes your code cleaner, easier to test, and flexible.