Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean instance of a shorter scope injected in a bean instance of a larger scope in CDI - how does it work?

Tags:

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?

like image 987
brandizzi Avatar asked Jul 05 '11 00:07

brandizzi


People also ask

What does the @ApplicationScoped annotation indicate?

Annotation Type ApplicationScoped. Specifies that a bean is application scoped.

How do you decide what should be the scope of the bean?

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.

How do you inject request in scoped bean?

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.

Which bean scope is used to keep Bean alive as long as request response lives?

@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.


1 Answers

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.

like image 86
Bozho Avatar answered Sep 18 '22 17:09

Bozho