Senior
@Service @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) class MyService { public String getMessage() { return "Hello from MyService! Instance: " + this.hashCode(); } } @RestController public class MyRestController { @Autowired private MyService myService; @GetMapping("/api/hello") public String hello() { return myService.getMessage(); } } curl [link] Hello from MyService! Instance: 56149 curl [link] Hello from MyService! Instance: ???????
sobes.tech AI
Answer from AI
The @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) annotation indicates that Spring should create a new instance of MyService for each bean request. However, in your MyRestController, the MyService bean is injected via a field using @Autowired — this happens only once when the controller is created (which is by default a singleton). As a result, despite the prototype scope, the same instance of MyService is always used in the controller.
Therefore, on repeated calls to /api/hello, you will see the same hash code of the instance.
To get a new instance of MyService on each call, you can:
- Inject
ObjectProvider<MyService>orApplicationContextand manually request the bean inside the method. - Use a
@Lookupmethod to obtain a new instance.
Example with ObjectProvider:
@RestController
public class MyRestController {
@Autowired
private ObjectProvider<MyService> myServiceProvider;
@GetMapping("/api/hello")
public String hello() {
MyService myService = myServiceProvider.getObject();
return myService.getMessage();
}
}
This way, a new MyService instance will be created each time hello() is called.