Junior — Middle
What is the role of the @Service annotation in Spring and why is it used?
sobes.tech AI
Answer from AI
The @Service annotation in Spring is used to denote a class as a service component of business logic. It is a specialized form of the @Component annotation, which allows Spring to automatically detect and register such classes in the application context through component scanning.
Using @Service helps to:
- Semantically distinguish application layers (e.g., controllers, services, repositories).
- Enable aspects (e.g., transactions) to be applied to business logic.
- Improve code readability by indicating that the class contains business logic.
Example:
@Service
public class UserService {
public User findUserById(Long id) {
// business logic
}
}