Theodora Fragkouli

About Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis.

Java EE CDI bean scopes

Contexts and Dependency Injection (CDI) for the Java EE platform is a feature that helps to bind together the web tier and the transactional tier of the Java EE platform. CDI is a set of services that, used together, make it easy for developers to use enterprise beans along with JavaServer Faces technology in web applications.

In CDI, a bean is a source of contextual objects that define application state and/or logic. A Java EE component is a bean if the lifecycle of its instances may be managed by the container according to the lifecycle context model defined in the CDI specification.

A managed bean is implemented by a Java class, which is called its bean class. A top-level Java class is a managed bean if it is defined to be a managed bean by any other Java EE technology specification, such as the JavaServer Faces technology specification.

When we need to use a bean that injects another bean class in a web application, the bean needs to be able to hold state over the duration of the user’s interaction with the application. The way to define this state is to give the bean a scope. A scope gives an object a well-defined lifecycle context. A scoped object can be automatically created when it is needed and automatically destroyed when the context in which it was created ends. Moreover, its state is automatically shared by any clients that execute in the same context.
When we create a Java EE component that is a managed bean, it becomes a scoped object, which exists in a well-defined lifecycle context. The scopes provided by CDI are presented in the table below:

cdi

1. Request – @RequestScoped

This scope describes a user’s interaction with a web application in a single HTTP request. The instance of the @RequestScoped annotated bean has an HTTP request lifecycle.

2. Session – @SessionScoped

This scope desrcibes a user’s interaction with a web application across multiple HTTP requests.

3. Application – @ApplicationScoped

In this case the state is shared across all users’ interactions with a web application. The container provides the same instance of the @ApplicationScoped annotated bean to all client requests.

4. Conversation – @ConversationScoped

This scope describes a user’s interaction with a JavaServer Faces application, within explicit developer-controlled boundaries that extend the scope across multiple invocations of the JavaServer Faces lifecycle. All long-running conversations are scoped to a particular HTTP servlet session and may not cross session boundaries.

Note that with ConversationScoped beans we achieve the same functionality we need from a ViewScoped JSF bean. In addition, with the ConversationScoped beans we can maintain the same conversation – or state – between distinct page requests. But when we leave a conversation without it, the managed bean will stay active until it times out.

A thing to notice is that beans that use session or conversation scope must be serializable. This is because the the container passivates the HTTP session from time to time, so when the session is activated again the beans’ state must be retrieved.

5. Singleton – @Singleton pseudo-scope

This is a pseudo-scope. It defines that a bean is once instantiated. When a CDI managed bean is injected into another bean, the CDI container makes use of a proxy. The proxy is the one to handle calls to the bean. Though, @Singleton annotated beans don’t have a proxy object. Clients hold a direct reference to the singleton instance. So, what happens when a client is serialized ? We must ensure that the singleton bean remains a singleton. To do so there are a fiew ways, such as, have the singleton bean implement writeResolve() and readReplace() (as defined by the Java serialization specification), make sure the client keeps only a transient reference to the singleton bean, or give the client a reference of type Instance<X> where X is the bean type of the singleton bean.

6. Dependent – @Dependent pseudo-scope

This pseudo-scope means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean). This is the default scope for a bean which does not explicitly declare a scope type. 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.

All predefined scopes except @Dependent are contextual scopes. CDI places beans of contextual scope in the context whose lifecycle is defined by the Java EE specifications. For example, a session context and its beans exist during the lifetime of an HTTP session. Injected references to the beans are contextually aware. The references always apply to the bean that is associated with the context for the thread that is making the reference. The CDI container ensures that the objects are created and injected at the correct time as determined by the scope that is specified for these objects.
You can also define and implement custom scopes. They can be used by those who implement and extend the CDI specification.
 
This was a tutorial of all bean scoped provided by CDI.
 
References:

Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Java EE CDI bean scopes"

  1. Binh Thanh Nguyen says:

    Thanks, nice post. It help me a lot.

Leave a Reply


five + = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books