Consider the following request-scoped CDI bean:
@RequestScoped public class RequestScopedBean { // ... }
Now, I inject it in a application-scoped bean:
@ApplicationScoped public class ApplicationScopedBean { @Inject private RequestScopedBean requestScopedBean; // ... }
I ran this code and noted that the request-scoped bean instance is different between two requests but the application-scoped bean instance is the same. My doubt is: how does this work? Is the request-scoped bean instance reattributed to the application-scoped field at each request? Or the proxy of the application-scoped bean just changes between requests?
Annotation Type ApplicationScoped. Specifies that a bean is application scoped.
If you place a managed bean into request scope, a new instance is created with each request. It is worth considering request scope if you are concerned about the cost of session scope storage. ApplicationScope: The application scope persists for the entire duration of the web application.
As singleton beans are injected only once per their lifetime you need to provide scoped beans as proxies which takes care of that. @RequestScope is a meta-annotation on @Scope that 1) sets the scope to "request" and 2) sets the proxyMode to ScopedProxyMode.
@SessionScoped Bean lives as long as the HTTP session lives. It gets created upon the first HTTP request involving this bean in the session and gets destroyed when the HTTP session is invalidated.
In CDI each injected object is actually a proxy. So in that case, the proxy probably holds a reference to the RequestContext
and on each method invocation gets the correct bean instance.
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