What are the main differences between the annotations @Controller, @Service, @Component, and @Repository in Spring?
sobes.tech AI
Answer from AI
In Spring Framework, annotations @Controller, @Service, @Component, and @Repository are used to mark classes and register them as beans in the Spring context, but they have different semantic meanings:
-
@Component — the basic annotation for any Spring component. Used for general classes that do not fit into other categories.
-
@Controller — a specialized component indicating a class that handles HTTP requests in an MVC application. Usually contains methods with @RequestMapping annotations.
-
@Service — indicates a service layer where business logic is implemented. Helps separate logic from controllers and repositories.
-
@Repository — an annotation for the data access layer (DAO). Besides registering the bean, it also translates data access exceptions into Spring's unified exceptions (DataAccessException).
Example:
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/users")
public String listUsers(Model model) {
model.addAttribute("users", userService.getAllUsers());
return "userList";
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
Thus, annotations help structure the application and improve code readability.