36.2. Scopes and contexts

Seam 2 provides a fixed set of contexts, as listed in the table below. Any java type can be stored in a context. Session and conversation contexts require the values to be serializable. In Seam 2, the scope of a component is defined using one of the values of the ScopeType enumeration, for example @Scope(ScopeType.SESSION).

CDI provides a similar set of contexts. This set can be extended by additional scopes provided by portable extensions that implement the required SPI. In CDI, each scope has an associated annotation, which consists of the scope name suffixed by Scoped, for example @SessionScoped.

CDI scopes are split into two groups:
  • Normal scopes - Implemented using dynamic proxies, the client receives a dynamic proxy for the contextual object. Every time a method is invoked on a proxy, the container guarantees that the method is invoked on the actual contextual instance. Most of the built-in CDI scopes are normal scopes.
  • Pseudo-scopes - Client proxies are not required for pseudo-scopes. CDI provides single built-in pseudo-scope @Dependent.

As a result of using dynamic proxies for implementing normal scopes (every scope except for @Dependent), every managed bean bound to a normal scope is required to be proxyable. The exact definition of a proxyable bean is defined in the specification. This may be a problem for legacy applications that use unproxyable beans, for example an instance of java.lang.String bound to the session scope. Possible solutions include the following:
  • making the bean proxyable (for example, adding a non-private no-arg constructor or removing the final modifier of a class or method)
  • creating a holder object that wraps the unproxyable object but is itself proxyable
  • using @Dependent scope instead of a normal scope if possible

Table 36.1. Corresponding Seam 2 and CDI Scopes

Seam 2 Scope CDI Scope

Event

Request

Session

Session

Stateless

No direct match. The stateless scope is used primarily for Stateless Session Beans (EJB) in Seam 2. A Stateless session bean can be bound to the @Dependent context in a CDI application.

No direct match.

Dependent - new instance for each injection point.

Page

No direct match.

Conversation
No direct match. There are several alternatives which help to maintain conversational state:
  • CDI Conversation scope keeps conversational state between many requests but needs to be programmatically started and stopped.
  • JSF Flash scope keeps state between two requests and possibly different views.
  • DeltaSpike Grouped Conversation scope keeps state per-window, starts automatically when a grouped-conversation-scoped bean is accessed, and maintains separate conversations for each bean or groups of beans.