Sobes.tech
Senior

What is the difference between the annotations @Component, @Service, @Controller in Spring?

sobes.tech AI

Answer from AI

In Spring, the annotations @Component, @Service, and @Controller serve to register classes as Spring beans but have different semantic purposes:

  • @Component — a basic, universal annotation for any component that should be managed by the Spring container. Used when the class does not fit into more specialized roles.

  • @Service — a specialized annotation for the service layer. It indicates that the class contains business logic. Semantically helps to separate application layers and can be used for additional aspects, such as transactions.

  • @Controller — an annotation for controllers in MVC applications. Responsible for handling HTTP requests and returning views or data.

Example:

@Component
public class UtilityComponent {
    // helper methods
}

@Service
public class UserService {
    // business logic
}

@Controller
public class UserController {
    // handling HTTP requests
}

Thus, the main difference is semantic and helps to structure the application and clarify the roles of components.