What are the differences between the annotations @Component, @Controller, @Repository, and @Service in Spring, and what are their purposes?
sobes.tech AI
Answer from AI
In Spring, the annotations @Component, @Controller, @Repository, and @Service are used to mark classes as beans and serve different purposes:
-
@Component— a basic annotation for any Spring component. Used when a class does not fit into other categories. -
@Controller— a specialized component for web controller layers. Handles HTTP requests and returns responses. -
@Service— indicates a service layer where business logic is implemented. Helps separate logic from controllers and repositories. -
@Repository— data access layer. Besides marking, Spring handles database-related exceptions and translates them into its own exceptions.
Thus, these annotations help structure the application into layers and provide Spring with additional information for bean processing.