Understanding Beans in Spring: The Backbone of a Spring Application

Published: (December 29, 2025 at 09:31 AM EST)
2 min read
Source: Dev.to

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

  1. Bean Created – instance is instantiated.
  2. Dependency Injection – dependencies are injected.
  3. Bean Initialized – any initialization callbacks are invoked.
  4. Bean is Used – the bean is ready for use by the application.
  5. 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.

Back to Blog

Related posts

Read more »

Spring Cloud Gateway: Basic Example

!Cover image for Spring Cloud Gateway: Basic Examplehttps://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fd...