22
votes

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?

1
@jangroth 4.9 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
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

1 Answers

16
votes

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.