Junior — Middle
What is the purpose of annotations @Component, @Repository, and @Service in Spring, and how do they differ?
sobes.tech AI
Answer from AI
Annotations @Component, @Repository, and @Service in Spring are used for automatic detection and registration of components in the application context (dependency injection).
- @Component — a basic annotation for any Spring component. Marks a class as a Spring bean.
- @Repository — a specialized component intended for the data access layer. Besides registering as a bean, Spring can automatically handle database exceptions and translate them into unified Spring exceptions.
- @Service — an annotation for the service layer, indicating business logic. Mainly used for semantic separation of code and can be used for additional aspects, such as transactions.
Example:
@Repository
public class UserRepository { ... }
@Service
public class UserService { ... }
@Component
public class UtilityComponent { ... }