@Component Vs @Repository Vs @Service Vs @Controller Vs @RestController

In Spring, @Repository@Service@Component@Controller, and @RestController are specialized annotations used to define Spring-managed beans. Each has a specific purpose and usage, making it easier to write clear and maintainable code.

Here’s the difference between them:


1. @Component:

  • Purpose: A generic stereotype annotation for any Spring-managed component or bean. It indicates that a class is a candidate for Spring’s component scanning.

  • Usage: Use this when the class doesn’t fit the @Controller@Service, or @Repository stereotypes.

  • Example:

    @Component
    public class MyUtility {
        public String process(String input) {
            return input.toUpperCase();
        }
    }
    

2. @Service:

  • Purpose: Indicates that a class provides business logic or service functionality. It is a specialized @Component with additional semantics for service-level operations.

  • Usage: Use this to annotate service layer classes.

  • Example:

    @Service
    public class UserService {
        public User findUserById(Long id) {
            // Business logic
            return new User();
        }
    }
    

3. @Repository:

  • Purpose: Indicates that a class is a Data Access Object (DAO). Spring automatically translates database-related exceptions to DataAccessException.

  • Usage: Use this to annotate persistence layer classes that interact with the database.

  • Additional Features: Provides database exception translation.

  • Example:

    @Repository
    public class UserRepository {
        public List<User> findAll() {
            // Database operations
            return new ArrayList<>();
        }
    }
    

4. @Controller:

  • Purpose: Indicates that a class is a controller in the Spring MVC web layer. It is responsible for handling HTTP requests and returning views.

  • Usage: Use this to define controller classes for traditional server-side rendered applications (e.g., Thymeleaf, JSP).

  • Example:

    @Controller
    public class HomeController {
        @GetMapping("/home")
        public String home() {
            return "home"; // Returns view name
        }
    }
    

5. @RestController:

  • Purpose: A convenience annotation that combines @Controller and @ResponseBody. It is used for RESTful web services where the responses are directly written to the HTTP response body as JSON or XML.

  • Usage: Use this to build REST APIs.

  • Example:

    @RestController
    public class UserRestController {
        @GetMapping("/users")
        public List<User> getUsers() {
            return List.of(new User("John"), new User("Jane"));
        }
    }
    

Summary of Differences:

AnnotationLayerPurposeResponse TypeSpecialized?
@ComponentGenericGeneral-purpose component or beanN/ANo
@ServiceServiceBusiness logic or service operationsN/AYes
@RepositoryPersistenceData access and database interactionN/AYes
@ControllerWebHandles HTTP requests for MVC appsView (e.g., HTML)Yes
@RestControllerWebRESTful APIs, direct response to HTTP bodyJSON/XMLYes

Key Points:

  • @Component is the most generic and can be used for any Spring bean.
  • @Service@Repository@Controller, and @RestController are specialized forms of @Component with additional semantics or functionality specific to their roles.
  • Use specialized annotations for better readability and understanding of the code’s purpose.

Post a Comment

Previous Post Next Post