Middle
What is the difference between the annotations @Repository, @Component, @Controller, and @Service in Spring Framework?
sobes.tech AI
Answer from AI
Difference in semantics and purpose:
@Component: The basic annotation indicating a class as a managed Spring component. Spring scans such classes and creates beans.@Repository: A specialization of@Component, intended for classes in the data access layer (DAO). Spring provides additional functionality for such beans, such as automatic exception translation.@Service: A specialization of@Component, intended for classes in the business logic layer. Used to denote services that perform specific business operations.@Controller: A specialization of@Component, intended for classes handling web requests in MVC architecture. Usually used together with request mapping annotations (@RequestMapping,@GetMapping,@PostMapping, etc.).
All these annotations are stereotype annotations. They do not provide new functionality by themselves, except facilitating component scanning. Their main advantage is improving code readability and clarity of the application's structure. Spring can also apply specific auto-configurations or providers for beans marked with these annotations.