CDI Bean Scope

Scopes

bean scopes: defines lifecycle of bean that is injected into another class; container automatically create / destroy / share scoped objects

  • @RequestScoped - in a single user HTTP request

    • no need to be serializable

  • @SessionScoped

    • in a user's interaction across multiple HTTP requests (a shopping cart)

    • must be serializable

  • @ApplicationScoped

    • shared state across all users' interactions

    • must be serializable

  • @Dependent

    • default scope if none is specified

    • an object exists to serve exactly one client bean and has the same lifecycle as that client bean

    • (my interpretation) one master one servant, created a new instance each time requested

  • @ConversationScoped

    • a user's interaction with a servlet including JSF applications

    • the conversation scope exists within developer controlled boundaries that extends across multiple requests for a long running conversations

    • scoped to a particular HTTP servlet session and may not cross sessionboundaries

    • must be serializable

  • Custom defined scopes (advanced topic)

Passivation and passivating scopes (see http://docs.jboss.org/cdi/spec/1.0/html/contexts.html)

Passivation: idle, stateful object temporarily transferred from memory to some secondary storage (hard-disk)

Passivation capable (not capable):

  • stateful session beans

  • (not) stateless and singleton

  • managed bean that is serializable (and all interceptors / decorators serializable)

  • producer method, if always returns passivation capable value

  • producer field, if always refers to a passivation capable value

  • PassivationCapable (interface)

Passivation capable dependencies: (skipped for now)

Passivating scopes: requires

  • beans with the scope are passivation capable

  • implementations of Contextual passed to any context object for the scope are passivation capable

Built-in scopes that are passivating scopes:

  • session

  • conversation

Java EE component scopes:

  • Singletons

  • Statless

  • Objects to be explicitly created / destroyed by client:

      • JavaBeans components

      • stateful session beans

    • state is shared by explicit reference passing between clients

  • However, if a Java EE component is a managed bean, it becomes a scoped object