Category: java
What is a Spring Bean?
Published on 24 Jul 2026
Explanation
A Spring Bean is an object created, configured, and managed by the Spring IoC (Inversion of Control) container. Beans are automatically detected during component scanning and are available throughout the application using Dependency Injection.
Code:
@Service
public class StudentService {
}
Explanation
A Spring Bean goes through several lifecycle phases: instantiation, dependency injection, initialization, usage, and destruction. Spring manages these phases automatically, allowing developers to focus on business logic instead of object management.
Code:
Bean Creation
β
Dependency Injection
β
@PostConstruct
β
Bean Ready
β
@PreDestroy
Explanation
Dependency Injection is a design pattern where Spring automatically provides required objects instead of creating them manually. Constructor Injection is the recommended approach because it promotes immutability and simplifies unit testing.
Code:
@Service
public class StudentService {
private final StudentRepository repository;
public StudentService(StudentRepository repository) {
this.repository = repository;
}
}
Explanation
Spring provides lifecycle callback annotations to execute custom logic during bean initialization and destruction. @PostConstruct runs after dependencies are injected, while @PreDestroy executes before the bean is removed from the container.
Code:
@Component
public class StudentBean {
@PostConstruct
public void init() {
System.out.println("Bean Initialized");
}
@PreDestroy
public void destroy() {
System.out.println("Bean Destroyed");
}
}
Explanation
Bean scope determines how many instances of a bean are created. Singleton creates one shared instance for the entire application, while Prototype creates a new instance every time the bean is requested from the Spring container.
Code:
@Component
@Scope("prototype")
public class Student {
}