Search code examples
jakarta-eecdi

What exactly is C in CDI?


All the materials I saw on CDI were confusing or hard to understand about the nature of the Contexts in the CDI.

Contexts: The ability to bind the lifecycle and interactions of stateful components to well-defined but extensible lifecycle contexts

This definition suggests that contexts have something to do with lifecycle;

A key part of CDI aside of its DI capabilities is its awarness of bean contexts and the management of bean lifecycle and dependencies within those contexts (such as @RequestScoped or @ConversationScoped).

After I read this explanation several times, I came to the conclusion, that it suggests that context is a place where beans can be injected; such as servlet container, ejb container or some Java SE container.

Is this a correct conclusion?


Solution

  • I also have difficulties to understand what is the context in the first place. Let me try to explain it in my own words.

    I usually think that a context is an object representing the environment of a process. Just like the environment of a bash shell and the OS which internally contain many environmental variables. It serves like a kind of global variables container that the process can access its variables easily at any time throughout the process lifecycle.

    Ideally, environment should be isolated with each other. Different process has their own isolated environment to work with such that a process cannot messed up with each other 's environment. Think that if I open two bash shell and I create a new variable in the shell1 , shell2 should not aware of this variable in their environment.

    In CDI, the process can be running an application, handling a HTTP request , handling a HTTP session or handling a conversation etc. which each type of process has their own context type which is application context , request context , session context and conversation context respectively. Each context internally can only contain object which the scoped is the same as the scope supported by that context (e.g Application context store @ApplicationScoped bean etc.)

    What CDI helps is to manage an environment for these process such that each process has their own isolated environment. For example, in case of session context , it internally keep all the @SessionScoped bean . CDI ensures that each HTTP session access their own isolated context correctly behind scene such thus the correct @SessionScoped beans are injected into the codes.