wasAsked.

What is the difference between @Component, @Service, @Repository and @Controller in Spring?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · Java, Spring Boot

Community answers

Posted by wasAsked editorial collection

All four annotations mark a class as a Spring-managed bean that component scanning will detect. @Service, @Repository and @Controller are specialisations of @Component: technically they register beans the same way, but they communicate the class's role and some add extra behaviour. @Component - The generic stereotype for any Spring-managed component that does not fit a more specific layer. - Examples: utility classes, mappers, schedulers, custom validators. @Component class SlugGenerator { String create(String title) { ... } } @Service - Marks a class in the business or service layer that contains business logic and orchestrates use cases. - Adds no special behaviour today beyond @Component, but documents intent and is a natural target for cross-cutting concerns (transactions, metrics, security annotations). @Service class OrderService { private final OrderRepository orders; OrderService(OrderRepository orders) { this.orders = orders; } @Transactional public Order place(OrderRequest req) { ... } } @Repository - Marks a data access component (DAO). - Adds behaviour: persistence exception translation. When a PersistenceExceptionTranslationPostProcessor is active (Spring Boot configures it), technology-specific exceptions (JPA, JDBC, Hibernate) thrown from @Repository beans are translated into Spring's DataAccessException hierarchy (for example DataIntegrityViolationException), so higher layers do not depend on the persistence technology. - Spring Data repository interfaces (extends JpaRepository) do not need the annotation — Spring creates implementations automatically. @Repository class JdbcOrderDao { ... } @Controller - Marks a web controller in Spring MVC that handles HTTP requests, usually returning view names for server-side rendering (Thymeleaf). - Detected by the MVC infrastructure for request mapping (@GetMapping, @PostMapping). @Controller class HomeController { @GetMapping("/") String home(Model model) { model.addAttribute("title", "Home"); return "home"; } } @RestController - A convenience annotation combining @Controller and @ResponseBody: return values are serialised directly to the response body (JSON) instead of being treated as view names. Used for REST APIs. @RestController @RequestMapping("/api/orders") class OrderController { @GetMapping("/{id}") OrderDto get(@PathVariable long id) { ... } } Summary of differences - @Component: generic bean; no extra behaviour. - @Service: business layer; semantic only. - @Repository: persistence layer; exception translation. - @Controller: web layer; request handling and views. - @RestController: web layer for APIs; @Controller plus @ResponseBody. Why use specific annotations instead of @Component everywhere - Clear architecture and readability: anyone can see a class's role. - Tooling and AOP pointcuts can target layers (for example, apply logging to all @Service classes). - Special behaviour where it exists (@Repository exception translation, @Controller request mapping). Related: @Configuration with @Bean methods is used to define beans for classes you cannot annotate (third-party libraries).

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics