Hackforge Academy

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 {

}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community