Junior — Middle
Can you explain the concept of a service within Spring and how it is used inside an application?
sobes.tech AI
Answer from AI
In Spring, a service is a component that contains the business logic of the application. Services are usually marked with the @Service annotation, which allows Spring to automatically detect and manage them through the dependency injection container (IoC).
Services are used to separate responsibilities: controllers handle HTTP requests, while services perform the main logic, such as working with databases, calculations, or integration with external systems.
Example of a service:
@Service
public class UserService {
public User findUserById(Long id) {
// logic to find user
}
}
In the controller, the service is injected via @Autowired or constructor:
@RestController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) {
return userService.findUserById(id);
}
}