Table of contents
1.
Introduction
2.
Vaadin CDI Scopes and Contexts
3.
CDI Scopes
3.1.
Normal Scopes
3.2.
Pseudo Scopes
3.3.
Using Push
4.
CDI Context
4.1.
VaadinServiceScoped Context
4.2.
VaadinSessionScoped Context
4.2.1.
Example
4.2.2.
Explanation 
4.3.
@UIScoped and @NormalUIScoped Contexts
4.3.1.
Example
4.3.2.
Explanation
4.3.3.
Example
4.4.
@RouteScoped and @NormalRouteScoped Contexts
4.4.1.
Example 
4.4.2.
Explanation
4.4.3.
Example 
4.4.4.
Explanation
5.
Frequently Asked Questions
5.1.
What is Vaadin?
5.2.
What are CDI Beans?
5.3.
What exactly are CDI Scopes?
5.4.
What exactly is CDI Context?
5.5.
What is VaadinServiceScoped Context?
6.
Conclusion 
Last Updated: Mar 27, 2024
Medium

Vaadin CDI Scopes and Contexts

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Suppose you want to learn how to create and deploy a contemporary web application entirely in Java. Vaadin Flow allows you to easily create web apps in pure Java without having to write any HTML or JavaScript. When utilizing Vaadin CDI, most framework-instantiated objects become managed beans. To obtain references to beans, the framework uses the CDI BeanManager. This indicates that they are complete CDI contextual instances. Now let's talk about Vaadin CDI Scopes and Contexts. 

The Vaadin CDI add-on adds extra contexts in addition to traditional CDI contexts.

Vaadin CDI Scopes and Contexts

The Vaadin CDI add-on adds extra contexts in addition to traditional CDI contexts.

Vaadin CDI contexts and Vaadin Spring scopes are essentially similar.

CDI Scopes

Normal Scopes

The majority of CDI scopes are standard scopes. This implies that the majority of managed bean calls are sent through a client proxy to the current instance. The context provides the active instance.

The VaadinServiceScopedVaadinSessionScopedNormalUIScoped, and NormalRouteScoped normal scopes are introduced by the Vaadin CDI add-on.

CDI Scopes

Pseudo Scopes

A pseudo scope is any scope that is not a conventional scope. Pseudo scopes include the normal @Dependent and @Singleton.

The @UIScoped and @RouteScoped pseudo scopes are also introduced by the Vaadin add-on.

Injection of a pseudo-scoped bean produces a direct reference to the object, although there are several drawbacks if proxies are not used:

  • Circular reference, such as injecting A to B and B to A, is ineffective.
  • Injecting into a bigger scope binds the currently active smaller scope's instance and ignores changes in the smaller scope. A @UIScoped bean, for example, will point to the same instance (even if its UI is closed) after being injected into a session scope, independent of the current UI.
     

Using Push

Vaadin contexts may be used with any push transport inside the UI.access() function.

Certain CDI default contexts, such as RequestScoped or SessionScoped, might be troublesome. In CDI, HttpServletRequest cannot be resolved over a WebSocket connection, despite the fact that this is required for an HTTP request, session, and conversation contexts. To prevent losing the standard contexts, use WebSocket XHR (the default) or LONG POLLING transport mode.

Regardless of push, background-thread contexts that rely on HTTP requests are not active.

CDI Context

VaadinServiceScoped Context

The beans are managed by the @VaadinServiceScoped context throughout the Vaadin service lifecycle. The service's lifespan is the same as that of its Vaadin servlet. 

You must use the @VaadinServiceEnabled annotation in conjunction with the @VaadinServiceScoped annotation for beans that are automatically picked up by VaadinService.

VaadinSessionScoped Context

During the Vaadin session lifetime, the beans are managed by the @VaadinSessionScoped context. This implies that the same bean instance is utilized throughout the Vaadin session.

Example

On route targets, use the @VaadinSessionScoped annotation. 

@Route("")
public class MyLayout extends Division
{
    @Inject
    public MyLayout(SessionService bean)
    {
        setText(bean.getText());
    }
}
 
@Route("editor")
public class Edit extends Division
{
    @Inject
    public Edit(SessionService bean)
    {
        setText(bean.getText());
    }
}

@VaadinSessionScoped
public class SessionService
{
    private String uid = UUID.randomUUID().toString();
    public String getText()
    {
        return "session " + uid;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Explanation 

  • Because it is session-scoped, if the application is accessed from the same Vaadin session, the same instance of SessionService is used.
  • The text in both tabs is the same if you open the root target in one and the editor target in another. This is due to the fact that the session is the same even while the tabs (and UI instances) vary.

 

CDI Context

@UIScoped and @NormalUIScoped Contexts

During the UI lifetime, the @UIScoped and @NormalUIScoped contexts control the beans. For components, use @UIScoped and @NormalUIScoped for other beans.

Example

On route targets, use the @NormalUIScoped annotation.

@Route (“”)
Public class MyLayout extends Division 
{
    @Inject
     Public MyLayout(UIService bean)
     {
        setText(bean.getText());
     }
}  

@Route("editor")
public class Edit extends Division 
{
    @Inject
    public Editor(UIService bean)
   {
        setText(bean.getText());
    }
}

@NormalUIScoped
public class UIService  
{
    private String uid = UUID.randomUUID().toString();
    public String getText()
    {
        return "ui " + uid;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Explanation

  • Because it is UI scoped, it uses the same UIService while in the same UI.
  • Because the UI instances differ, the text differs when you open the root target in one tab and the editor target in another.
  • The same bean instance is utilized with both @UIScoped and @NormalUIScoped in the same UI instance.
  • The text is the same if you travel to the editor instance via the router (or the UI instance, which delegates navigation to the router).

Example

Navigating to the editor's objective

public void edit()
{
getUI().get().navigate("editor");
}
You can also try this code with Online Java Compiler
Run Code

@RouteScoped and @NormalRouteScoped Contexts

During the Route lifespan, the beans are managed by @RouteScoped and @NormalRouteScoped. For Components, use @RouteScoped, and for other beans, use @NormalRouteScoped 

Both @RouteScoped and @NormalRouteScoped may be used in conjunction with the @RouteScopeOwner annotation to bind beans to router components (@Router, RouterLayoutHasErrorParameter). While the owner is still in the routing chain, all of the beans it owns are still in scope.

Example 

On route targets, use the @NormalRouteScoped annotation.

@Route("")
@RoutePrefix("parent")

public class PView extends Division
        implements RouterLayout 
{
    @Inject
    public PView(
            @RouteScopeOwner(PView.class)
            RouteService routeService) 
   {
        setText(routeService.getText());
    }
}

@Route(value = "child-a", layout = PView.class)
public class CAView extends Division 
{
    @Inject
    public CAView(
            @RouteScopeOwner(PView.class)
            RouteService routeService) 
   {
        setText(routeService.getText());
    }
}

@Route(value = "child-b", layout = PView.class)
public class CBView extends Division 
{
    @Inject
    public CBView(
            @RouteScopeOwner(PView.class)
            RouteService routeService) 
   {
        setText(routeService.getText());
    }
}

@NormalRouteScoped
@RouteScopeOwner(PView.class)
public class RouteService 
{
    private String uid = UUID.randomUUID().toString();
    public String getText() 
   {
        return "ui " + uid;
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Explanation

  • While you travel between PView, CAView, and CBView (paths:/parent, /parent/child-a, and/ parent/ child-b), they all utilise the same RouteService instance. The RouteService is similarly deleted when leaving the PView.
  • Despite the fact that @RouteScopeOwner is redundant because it is a CDI qualification, it must be defined on both the bean and the injection point.

 

Route components can be @RouteScoped as well. @RouteScopeOwner should point to a parent layout in this scenario. If you leave it out, the route becomes the owner.

Example 

The @RouteScoped annotation is applied to a @Route component.

@Route("scoped")
@RouteScoped
public class ScopedView extends Division {
    private void onMessage(
            @Observes(notifyObserver = IF_EXISTS)
            MessageEvent message) {
        setText(message.getText());
    }
}
You can also try this code with Online Java Compiler
Run Code

 

Explanation

  • The message is given to the previously browsed to ScopedView instance. If there is no instance of this bean on another view, the message is not delivered to it.

Frequently Asked Questions

What is Vaadin?

Vaadin is an open-source framework for developing contemporary web applications. It contains a vast component library and an easy-to-use Java API. It is also compatible with Spring.

What are CDI Beans?

CDI Beans are classes that CDI can Automatically instantiate, manage and inject to meet the requirement of the Other objects. CDI can manage and inject almost any Java Class.

What exactly are CDI Scopes?

When CDI initializes a managed bean, the bean is initialized in a highly particular scope. The lifespan of a bean is determined by the scope in which it is started. The following bean scopes are available through CDI: Update: Java EE 7 added three additional CDI bean scopes: TransactionScoped, FlowScoped, and ViewScoped.

What exactly is CDI Context?

In CDI, a context is a time interval during program execution where contextual objects may be used. It specifies when the CDI container generates and destroys objects, as well as how it connects instances of those objects.

Non-contextual objects are ones that are not associated with a CDI context.

What is VaadinServiceScoped Context?

The beans are managed by the @VaadinServiceScoped context throughout the Vaadin service lifecycle. The service's lifespan is the same as that of its Vaadin servlet. 

Conclusion 

In this article, we learned about the Vaadin CDI Scopes and Contexts, which includes types of CDI Scopes and CDI Contexts.

After reading about Vaadin CDI Scopes and Contexts, are you not feeling excited to read/explore more articles on the topic of Ruby? Don't worry; Coding Ninjas has you covered. To learn, see the Custom tag in JSF, The Merge Tag, and BorderLayout in Java.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and many more! 

Do upvote our blogs if you find them helpful and engaging!

thank you
Live masterclass