Understanding Beans in Spring: The Backbone of a Spring Application
Source: Dev.to
What is a Spring Bean?
A Spring Bean is an object that is created, configured, and managed by the Spring IoC (Inversion of Control) container. In simple terms:
- Spring creates the objects for you
- Spring manages their dependencies
- Spring controls their lifecycle
Beans form the core building blocks of a Spring application, and the entire application is essentially a collection of beans wired together.
How Are Beans Defined in Spring?
Using Stereotype Annotations
Common stereotype annotations:
@Component– generic component@Service– business logic layer@Repository– data access layer@Controller– web controller layer
These annotations tell Spring: “This class should be managed by the IoC container.”
Explicit Bean Declaration Using a Configuration Class
- The class is annotated with
@Configuration. - Methods inside the class define beans programmatically, e.g.:
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
This approach gives more control over how beans are created and configured, especially when customization is required.
Spring Bean Lifecycle
Bean Lifecycle Stages
- Bean Created – instance is instantiated.
- Dependency Injection – dependencies are injected.
- Bean Initialized – any initialization callbacks are invoked.
- Bean is Used – the bean is ready for use by the application.
- Bean Destroyed – destruction callbacks are executed before removal.
Bean Lifecycle Hooks
@PostConstruct– method called after dependency injection is complete.@PreDestroy– method called before the bean is removed from the container.
Scope of Spring Beans
Common Bean Scopes
singleton(default) – a single shared instance per Spring container.prototype– a new instance each time the bean is requested.request– one instance per HTTP request (web context).websocket– one instance per WebSocket session.
Understanding scope is important because it directly impacts memory usage, performance, and application behavior.
Why Beans Matter
- Dependency Injection – promotes loose coupling.
- Clean Architecture – separates concerns clearly.
- Testable and Maintainable – beans can be easily mocked or swapped in tests.
Once the concept of beans is clear, understanding other Spring features becomes much easier.