Loading

Quipoin Menu

Learn • Practice • Grow

spring / Spring Beans & Lifecycle
tutorial

Spring Beans & Lifecycle

A Spring Bean is simply an object that is managed by the Spring IoC container. Just like a chef prepares ingredients before cooking, Spring prepares (creates and wires) beans for you.

Beans are defined in a configuration file (XML, annotations, or Java config) and then instantiated, assembled, and managed by Spring.

Bean Lifecycle: When Spring creates a bean, it goes through several steps:


1. Instantiation (constructor called)
2. Populate properties (setter injection)
3. BeanNameAware's setBeanName()
4. BeanFactoryAware's setBeanFactory()
5. ApplicationContextAware's setApplicationContext() (if applicable)
6. BeanPostProcessor's postProcessBeforeInitialization()
7. @PostConstruct / init-method
8. BeanPostProcessor's postProcessAfterInitialization()
9. Bean is ready to use
10. When container shuts down: @PreDestroy / destroy-method
You can hook into the lifecycle by defining custom init and destroy methods:

public class MyBean {
public void init() {
System.out.println("Bean initialized");
}
public void destroy() {
System.out.println("Bean destroyed");
}
}
<bean id="myBean" class="MyBean" init-method="init" destroy-method="destroy"/>
Two Minute Drill
  • A Spring Bean is any object managed by the IoC container.
  • Beans are defined in configuration and created by Spring.
  • The bean lifecycle includes instantiation, property population, initialization callbacks, and destruction.
  • You can customize initialization and destruction using init-method and destroy-method (or annotations).

Need more clarification?

Drop us an email at career@quipoinfotech.com