Junior — Middle
When using @RestController, is a new instance of the service created for each HTTP request or is the same object used?
sobes.tech AI
Answer from AI
When using the @RestController annotation in Spring Boot services, they are typically singletons by default. This means that for each HTTP request, a new instance of the controller or service is not created; instead, the same object is used.
Spring manages the lifecycle of beans and by default creates them as singletons, which improves performance and conserves resources.
If you need to create a new instance for each request, you can change the scope of the bean, for example, using the @Scope("request") annotation.
Example:
@Service
public class MyService {
// singleton service by default
}
@RestController
public class MyController {
private final MyService myService;
public MyController(MyService myService) {
this.myService = myService;
}
@GetMapping("/hello")
public String hello() {
return "Hello";
}
}
Here, MyService and MyController are singletons, with one instance for the entire application.