@Component, @Service, @Repository and @Controller

Difficulty: Beginner

Question

What is the difference between @Component, @Service, @Repository, and @Controller? Are they functionally different?

Answer

This one sounds like a trick question, and honestly the honest answer is a bit anticlimactic. All four are stereotype annotations that tell Spring to register a class as a bean during component scanning. @Service, @Repository, and @Controller are all meta-annotated with @Component, which means Spring treats them as components at heart. The differences are about intent, a few special behaviours, and readability.

Imagine the departments in a hospital. Reception, doctors, records room, and billing are all staff, but their badges show which department they belong to. @Component is the generic staff badge for any bean that does not fit a specific layer, like a utility or a scheduler. @Controller marks the web layer, the class that receives HTTP requests. @Service marks the business logic layer, where rules such as calculating fees or validating a booking live. @Repository marks the persistence layer, the classes that talk to the database.

Beyond documentation, there are real behavioural differences in two places. @Repository activates persistence exception translation. When a class carries @Repository, Spring registers a PersistenceExceptionTranslationPostProcessor that wraps it in a proxy, converting vendor-specific exceptions such as Hibernate exceptions or SQLException into Spring's unified DataAccessException hierarchy. Your service layer then catches DataIntegrityViolationException without caring whether the underlying technology is JPA, JDBC, or MongoDB. With Spring Data JPA interfaces this is applied automatically, so you mostly see @Repository on hand-written DAO classes.

@Controller is detected by Spring MVC. The handler mapping looks for beans annotated with @Controller or @RequestMapping to build the URL mapping table. If you annotated a controller with just @Component, the mappings would not register, so this one is functionally required. @RestController is @Controller plus @ResponseBody. @Service, in contrast, currently has no extra behaviour; it is purely semantic, though the framework could add features in the future and it makes AOP pointcuts easier, for example targeting everything annotated @Service for logging.

How does Spring find them? @SpringBootApplication includes @ComponentScan, which scans the package of the main class and all sub-packages. A classic beginner bug is placing the main class in a sub-package, so beans in sibling packages are never found and you get NoSuchBeanDefinitionException. The fix is moving the main class to the root package or specifying scanBasePackages.

When asked for best practice, say you use the specific annotation that matches the layer, keep controllers thin, put business rules in services, and keep repositories focused on data access. Also mention that you can define beans without stereotypes using @Bean methods in a @Configuration class, which is the way to register third-party classes you cannot annotate.

Code examples

Layered stereotypes in action

@RestController
@RequestMapping("/api/students")
@RequiredArgsConstructor
class StudentController {
    private final StudentService service;

    @GetMapping("/{id}")
    public StudentDto get(@PathVariable Long id) { return service.find(id); }
}

@Service
@RequiredArgsConstructor
class StudentService {
    private final StudentRepository repo;

    public StudentDto find(Long id) {
        return repo.findById(id).map(StudentDto::from)
                   .orElseThrow(() -> new StudentNotFoundException(id));
    }
}

@Repository
interface StudentRepository extends JpaRepository<Student, Long> { }

@Component
class CsvExporter { /* generic helper that fits no layer */ }

Each annotation documents the layer; @Repository additionally enables exception translation, and @Controller is needed for MVC to map URLs.

Key points

Common follow-up questions

Interview tips

Concepts covered

Stereotype Annotations, Component Scan, Exception Translation, Layered Architecture

More Spring Boot questions