26

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?

brandizzi
  • 26,083
  • 8
  • 103
  • 158
  • 1
    @jangroth [4.9 Client Proxies](http://docs.jboss.org/weld/reference/latest/en-US/html/injection.html#_client_proxies) chapter gives an overview but doesn't explain how it really works. Specifically, what happens when a single `@ApplicationScoped` bean has a `@SessionScoped` bean injected, and receives two parallel invocations from `@RequestScoped` methods? – Alex Feb 25 '15 at 17:01
  • 2
    *You did notice* that the question was asked 4 years ago, and that CDI / Weld (and its documentation) have had a few version bumps in the meantime? ;) – Jan Groth Feb 25 '15 at 19:42

1 Answers1

20

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 3
    True in the core, but not in the detail. `DependentScoped` beans will never be proxied, as well as `SingletonScoped` beans. Both scopes are so-called pseudo scopes. – Jan Groth Jul 05 '11 at 09:29
  • Is application scope a pseudo scope? I'm not sure of that. Anyway, my point was about the particular example - request context. – Bozho Jul 05 '11 at 10:17
  • 1
    No, not ApplicationScope, but [SingletonScope](http://docs.jboss.org/weld/reference/latest/en-US/html/scopescontexts.html#d0e1923) is. That's why it's always better to use ApplicationScope :-) – Jan Groth Jul 05 '11 at 13:44
  • 3
    Just to clear this up for others, there is no such thing as SingletonScoped in CDI, there is the unloved step-child @javax.inject.Singleton which is inherited from "JSR-330 Dependency Injection for Java". It should be avoided at all cost, your need is most likely satisified by ApplicationScoped any way. – dngfng Feb 04 '16 at 21:48