Junior — Middle
What is the difference between Service, Controller, and Repository layers in Spring architecture?
sobes.tech AI
Answer from AI
In the architecture of Spring applications, the Service, Controller, and Repository layers serve different roles:
-
Controller — responsible for handling HTTP requests, receiving data from the user, and returning responses. It connects the external world with the internal logic of the application.
-
Service — contains the business logic of the application. It implements core operations, rules, and processes that do not depend on data storage or presentation details.
-
Repository — responsible for working with the database or other data sources. It implements CRUD operations and data queries.
Example:
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findUserById(id);
}
}
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User findUserById(Long id) {
// business logic, e.g., permission check
return userRepository.findById(id).orElse(null);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// data access methods
}
This separation improves support, testability, and scalability of the application.