0
0
Spring Bootframework~3 mins

Why @Component, @Service, @Repository, @Controller in Spring Boot? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how simple annotations can save you hours of tedious setup and prevent bugs!

The Scenario

Imagine building a web app where you have to manually create and connect every part like services, data access, and controllers by hand.

You write code to create objects, manage their lifecycles, and connect them all together.

The Problem

This manual wiring is slow, error-prone, and hard to maintain.

Changing one part means hunting through many files to update connections.

It's easy to forget to create or link something, causing bugs.

The Solution

Spring Boot's annotations like @Component, @Service, @Repository, and @Controller automatically tell the framework how to create and connect parts.

This means less manual work, fewer mistakes, and easier maintenance.

Before vs After
Before
UserService userService = new UserService();
UserRepository userRepository = new UserRepository();
userService.setUserRepository(userRepository);
After
@Service
public class UserService {
  @Autowired
  private UserRepository userRepository;
}
What It Enables

It enables automatic management and connection of app parts, so you can focus on writing business logic instead of wiring code.

Real Life Example

When building an online store, @Controller handles web requests, @Service processes orders, and @Repository manages database access--all connected automatically.

Key Takeaways

@Component marks a general bean for Spring to manage.

@Service marks a service layer bean for business logic.

@Repository marks a data access bean for database operations.

@Controller marks a web controller bean to handle HTTP requests.

These annotations reduce manual wiring and improve app structure.