Component Inspector
Click on any phase of the lifecycle diagram to understand how Spring manages your objects.
Simulation Legend
The Spring Bean Lifecycle
At the heart of the Spring Framework is the **IoC (Inversion of Control) Container**, represented by the `ApplicationContext`. Instead of your code constructing objects using the `new` keyword, Spring acts as a factory. It instantiates, configures, and manages the entire lifespan of these objects, which are called **Beans**.
Inversion of Control
You surrender control of object creation to the framework. You simply declare *what* you need (via interfaces/annotations), and Spring provides the fully configured implementation at runtime.
Dependency Injection
A specific form of IoC. When Spring creates Bean A, and Bean A needs Bean B to function, Spring automatically "injects" Bean B into Bean A (via constructors or setters) before Bean A is ready.
Lifecycle Phases in Detail
1. Instantiation & Dependency Injection
Spring reads your `@Component` classes or `@Bean` methods, uses reflection to call the constructor, and immediately injects required dependencies.
@Service
public class OrderService {
private final PaymentProcessor processor;
// Constructor Injection (Recommended)
@Autowired
public OrderService(PaymentProcessor processor) {
this.processor = processor; // Injected by Spring
}
}
2. Initialization Callbacks (@PostConstruct)
Once dependencies are injected, the bean isn't fully ready yet. You might need to open a file, validate properties, or warm up a cache. Spring calls initialization methods you define.
@Component
public class CacheManager {
@PostConstruct
public void initCache() {
// Runs AFTER dependencies are injected
System.out.println("Loading initial data into cache...");
}
}
3. BeanPostProcessors & AOP Proxies
This is where Spring's magic happens. `BeanPostProcessor`s are special hooks that can modify your bean *before* or *after* the initialization callbacks.
Crucially, if a bean requires AOP (Aspect-Oriented Programming) like `@Transactional`, `@Async`, or Method Security, Spring's `postProcessAfterInitialization` doesn't return your original object. It returns a dynamically generated **Proxy** object that wraps yours.
@Service
public class UserService {
@Transactional // Triggers proxy creation during lifecycle
public void createUser() {
// DB logic...
}
}
4. Destruction Callbacks (@PreDestroy)
When the application shuts down, singleton beans are given a chance to gracefully release resources, close connections, or save state.
@Component
public class DatabaseConnectionPool {
@PreDestroy
public void cleanup() {
// Runs before the bean is garbage collected by Spring
System.out.println("Closing all database connections...");
}
}