CDI - Contexts and Dependency Injection

Definition

CDI beans are classes that CDI can instantiate, manage, and inject automatically to satisfy the dependencies of other objects.

Contexts

This service enables you to bind the lifecycle and interactions of stateful components to well-defined but extensible lifecycle contexts.

Dependency Injection

This service enables you to inject components into an application in a type-safe way and to choose at deployment time which implementation of a particular interface to inject.

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface Informal {}
import javax.inject.Inject;

@Named("MyPrinter")
@RequestScoped
public class Printer {
  @Inject @Informal Greeting greeting;
}
Scopes
  • @RequestScoped
  • @SessionScoped
  • @ApplicationScoped
  • @Dependent
  • @ConversationScoped
Producer
@Produces @MaxNumber int getMaxNumber() {
    return maxNumber;
}
@Inject @MaxNumber private int maxNumber;
PostConstruct - PreDestroy
@PostConstruct
public void reset () {
    this.minimum = 0;
    this.userNumber = 0;
    this.remainingGuesses = 0;
    this.maximum = maxNumber;
    this.number = randomInt.get();
}
@PreDestroy

Liens>