Search code examples
dependency-injectioncdijava-ee-7weld

CDI Keeps all Injected tree references of SessionScoped beans?


I am starting a new project with JavaEE 7 and declared a Sessionscoped bean to maintain the web logged user information in session.

The UserSessionBean, as I named it, is intended to be lightweight - trying to avoid lots of data to be kept in the session by Weld. But in some cases I need to get all user information, so added a getUser() method which must query and retrieve a UserEntity from JPA. In order for the method to do its job, I need to @Inject other resources onto the UserSessionBean.

My question is: These dependant resources will be kept and serialised within the UserSessionBean by Weld until the context is destroyed?

The weld documentation says this:

An instance of a dependent bean is never shared between different clients or different injection points. It is strictly a dependent object of some other object. It is instantiated when the object it belongs to is created, and destroyed when the object it belongs to is destroyed.

That makes me think the all SessionBean tree is kept by weld during session life, but how can I keep a lightweight SessionBean and use injected CDI resources on it?


Solution

  • Since what you're injecting are also CDI beans, it is not the beans themselves that get serialised, but their lightweight proxies. Upon deserialisation, the proxies dynamically resolve the correct beans for whatever scope they are. See section 5.4 Client Proxies of the CDI1.0 spec. Hence, your bean is as lightweight as possible.