How can I set up a bean which will created once per request.
I Tried to do like this :
@Component
@Scope(value = "request")
public class TestBean {
@PostConstruct
public void init() {
System.out.println("start request");
}
@PreDestroy
public void onDestroy() {
System.out.println("ends request");
}
}
Thanks.
A request-scoped bean is an object managed by Spring, for which the framework creates a new instance for every HTTP request. The app can use the instance only for the request that created it. Any new HTTP request (from the same or other clients) creates and uses a different instance of the same class (figure 2).
If a component is marked with request scope, simultaneous requests each see a different instance of the component. This is true even when the same session sends two requests simultaneously; each request gets a pointer to a separate object.
A request can be made to the bean instance either programmatically using getBean() method or by XML for Dependency Injection of secondary type. Generally, we use the prototype scope for all beans that are stateful, while the singleton scope is used for the stateless beans.
The request scope creates a bean instance for a single HTTP request, while the session scope creates a bean instance for an HTTP Session. The application scope creates the bean instance for the lifecycle of a ServletContext, and the websocket scope creates it for a particular WebSocket session.
Try this
@Scope(value="request", proxyMode= ScopedProxyMode.TARGET_CLASS)
For more details see this blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With