Question
Spring @Component vs @Repository vs @Service: What's the Difference?
Question
In Spring, can @Component, @Repository, and @Service be used interchangeably, or do they provide specific functionality beyond simply marking a class?
For example, if a service class is annotated with @Service and I change it to @Component, will it still behave the same way?
Does the chosen annotation affect the behavior and functionality of the class, or is it mainly used for organization and readability?
Short Answer
By the end of this page, you will understand how Spring stereotype annotations work, what @Component, @Service, and @Repository have in common, and where they differ. You will also learn when they are interchangeable, when they are not, and why using the most specific annotation improves code clarity and framework integration.
Concept
Spring uses stereotype annotations to mark classes as beans that should be detected during component scanning and managed by the Spring container.
The three annotations in this question are closely related:
@Component
@Service
@Repository
The core idea
@Service and @Repository are specialized forms of @Component.
That means:
- A class annotated with any of them can usually be discovered by component scanning.
- Spring can create an object for that class and manage its lifecycle as a bean.
- You can inject that bean into other classes using dependency injection.
What they have in common
All three typically:
- Register the class as a Spring bean
- Allow dependency injection
- Participate in component scanning
- Represent application-layer classes managed by Spring
What makes them different
The difference is mostly about meaning and framework behavior.
@Component
This is the most general stereotype. It says:
- "This class is a Spring-managed component."
Use it when the class does not clearly belong to a more specific role.
Mental Model
Think of @Component as a general label that says, "Put this object on Spring's staff list."
Then think of @Service and @Repository as job titles:
@Component= employee@Service= business manager@Repository= database specialist
All of them are employees, so they can enter the building and do work. But the job title tells everyone what role they play.
In one case, the job title can also change behavior:
@Repositorynot only says "database specialist"- it also allows Spring to treat certain database errors in a special way
So the labels are not only decorative. They are partly descriptive, and in some cases, they affect framework behavior too.
Syntax and Examples
Basic syntax
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.stereotype.Repository;
@Component
public class EmailFormatter {
}
@Service
public class OrderService {
}
@Repository
public class OrderRepository {
}
Each of these classes can be discovered by component scanning and registered as a Spring bean.
Example with dependency injection
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
@Repository
public class UserRepository {
public String findUsernameById(long id) {
return "alice";
}
}
@Service
public class UserService {
private final UserRepository userRepository;
{
.userRepository = userRepository;
}
String {
userRepository.findUsernameById(id).toUpperCase();
}
}
Step by Step Execution
Consider this example:
@Repository
public class ProductRepository {
public String findById(int id) {
return "Laptop";
}
}
@Service
public class ProductService {
private final ProductRepository productRepository;
public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}
public String getProductLabel(int id) {
String product = productRepository.findById(id);
return "Product: " + product;
}
}
Step by step
1. Spring scans the package
Spring looks for classes annotated with stereotypes such as:
@Component@Service@Repository
Real World Use Cases
Where @Component is used
Use @Component for general-purpose classes that do not clearly belong to the service or persistence layer.
Examples:
- utility classes managed by Spring
- custom validators
- token generators
- file parsers
- scheduled task helpers
@Component
public class SlugGenerator {
public String toSlug(String text) {
return text.toLowerCase().replace(" ", "-");
}
}
Where @Service is used
Use @Service for business rules and application workflows.
Examples:
- order processing
- payment logic
- account registration rules
- email sending coordination
- report generation
@Service
public class PaymentService {
public boolean processPayment {
amount > ;
}
}
Real Codebase Usage
In real projects, developers rarely choose these annotations randomly. They use them to communicate architecture and to support framework conventions.
Common pattern: layered architecture
@RestController
public class OrderController {
private final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
}
@Service
public class OrderService {
private final OrderRepository orderRepository;
public OrderService(OrderRepository orderRepository) {
this.orderRepository = orderRepository;
}
}
@Repository
public class OrderRepository {
}
This tells readers immediately what each class is responsible for.
Guard clauses and validation in services
Services often contain checks before calling repositories:
@Service
public class AccountService {
{
(email == || email.isBlank()) {
();
}
}
}
Common Mistakes
1. Using @Component everywhere
This works technically in many cases, but it hides the role of each class.
Less clear
@Component
public class InvoiceService {
}
@Component
public class InvoiceRepository {
}
Better
@Service
public class InvoiceService {
}
@Repository
public class InvoiceRepository {
}
2. Thinking @Service adds major built-in business logic features
Beginners sometimes assume @Service automatically changes how methods run.
Usually, it does not add special runtime behavior by itself. It mainly provides semantic meaning as a specialized @Component.
3. Replacing @Repository with @Component for database classes
This can be a real mistake because repository-specific exception translation may no longer apply.
Comparisons
Quick comparison
| Annotation | Is it a Spring bean stereotype? | Main purpose | Extra behavior | Best use |
|---|---|---|---|---|
@Component | Yes | General-purpose Spring-managed class | Usually none specific | Helpers, utilities, generic components |
@Service | Yes | Business logic layer | Mostly semantic in common usage | Services, workflows, application rules |
@Repository | Yes | Persistence/data access layer | Exception translation for persistence errors | DAO, JPA, JDBC, database access |
@Service vs @Component
Cheat Sheet
Quick rules
@Component= general Spring-managed bean@Service= business logic bean@Repository= data access bean@Serviceand@Repositoryare specialized versions of@Component
What all three do
- make the class eligible for component scanning
- register it as a Spring bean
- allow dependency injection
Important difference
@Repositorycan enable persistence exception translation@Serviceis usually mainly semantic and architectural
Good defaults
@Component // generic helper or utility
@Service // business logic
@Repository // database access
Typical layered structure
@RestController
class UserController {}
{}
{}
FAQ
Can @Component, @Service, and @Repository all create Spring beans?
Yes. All three can mark a class for component scanning so Spring can create and manage it as a bean.
Is @Service just a special kind of @Component?
Yes. @Service is a specialization of @Component, mainly used to indicate business logic.
Does changing @Service to @Component usually break anything?
Usually no, as long as component scanning still finds the class. The bean will typically behave the same way.
Why should I use @Repository instead of @Component for database classes?
Because @Repository clearly marks persistence code and can enable Spring's persistence exception translation.
Does @Service provide extra runtime features by default?
In common usage, not much. Its biggest value is semantic clarity and better architecture communication.
Are these annotations required for dependency injection?
A class usually needs to be registered as a bean somehow. These annotations are one common way to do that through component scanning.
Mini Project
Description
Build a small layered Spring example with a utility component, a service, and a repository. This project helps you see where each stereotype belongs and how the classes work together in a realistic structure.
Goal
Create a simple user lookup flow where a service calls a repository and also uses a general-purpose component.
Requirements
- Create one class annotated with
@Componentfor formatting usernames - Create one class annotated with
@Repositorythat returns a hardcoded username - Create one class annotated with
@Servicethat uses both classes - Add one runner or test method that calls the service and prints the result
Keep learning
Related questions
Avoiding Java Code in JSP with JSP 2: EL and JSTL Explained
Learn how to avoid Java scriptlets in JSP 2 using Expression Language and JSTL, with examples, best practices, and common mistakes.
Choosing a @NotNull Annotation in Java: Validation vs Static Analysis
Learn how Java @NotNull annotations differ, when to use each one, and how to choose between validation, IDE hints, and static analysis tools.
Convert a Java Stack Trace to a String
Learn how to convert a Java exception stack trace to a string using StringWriter and PrintWriter, with examples and common mistakes.