Mastering Java EE Development with WildFly
上QQ阅读APP看书,第一时间看更新

Scopes

Scopes establish the lifecycle of a bean. A bean according to its scope can always exist in memory or be destroyed after the invocation.

A scope is an annotation that extends the @Scope or the @NormalScope annotations. The scope is defined in a bean by annotating the class, producer method or field with a scope type or a stereotype that defines a default scope. Here is an example:

@ConversationScoped
public class ConversationBean ...

A class, producer method or field of a bean can specify at most one scope annotation.

If the bean does not explicitly declare a stereotype with a default scope or another scope, the scope default becomes automatically @Dependent.

A normal scope is a scope annotated with @NormalScope. These are contextual scopes having a client proxy. A contextual scope implements a contextual interface, which provides operations to create and destroy contextual instances of a certain types (create() and destroy()). During create() and destroy(), the contextual interface uses the CreationalContext operations, push() and release(). Contextual instances with a particular scope of any contextual type are obtained via context interface operations (for example, get()). Samples of normal scopes are:

  • @ApplicationScope
  • @SessionScope
  • @RequestScope
  • @ConversationScope

A pseudo-scope is a scope annotated with @Scope. So, a dependent scope is a pseudo-scope. This is a non-contextual scope with no client proxy. Well, the "no client proxy" part should be highlighted, ... and it is! CDI managed beans can be successfully used in JavaServer Faces (JSF), but there is a problem with CDI managed beans annotated with @Singleton. They don't use proxy objects! Since there is a direct reference instead of a proxy we have some serialization issues. When singleton scoped beans are injected into client beans, the client beans will get a direct reference to the injected bean. So, if a client bean is serializable (for example, SessionScoped), it must ensure that the injected singleton bean serialization is accomplished correctly. Samples of pseudo-scopes are:

  • @Dependent
  • @Singleton

A singleton is taken by the common annotation specifications that we will see after javax.inject.Singleton. It is a simple singleton, not to be confused with the javax.ejb.Singleton, a more complex singleton working inside an EJB container. This annotation will be seen in Chapter 4 , Implementing Business logic.