Jakarta CDI - Intermediate Lab 1
In this lab, we will create an object and destroy objects using the Produces and Dispose annotations, respectively.
1. Create the NumberProducer class
Steps
- Open the
01-jakarta-eeproject and navigate to thesrc/main/java - Create a package named
producerin theexpert.os.labs.persistence.cidpackage - Create a class called
NumberProducerin theexpert.os.labs.persistence.cid.producerpackage - Annotate it with the
@ApplicationScopedfrom thejakarta.enterprise.contextpackage - Add a producer method, annotating it with
@Producesfrom thejakarta.enterprise.injectpackage and generate a randomBigDecimalvalue within the range [1, 100] using theThreadLocalRandomand return it - Add a disposer method named
destroy()to remove the value from the class where it has avalueparameter annotated with@Disposesfrom thejakarta.enterprise.injectpackage
Solution
Click to see...
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Disposes;
import jakarta.enterprise.inject.Produces;
import java.math.BigDecimal;
import java.util.concurrent.ThreadLocalRandom;
@ApplicationScoped
public class NumberProducer {
@Produces
public BigDecimal producer() {
ThreadLocalRandom random = ThreadLocalRandom.current();
double nextDouble = random.nextInt(1, 100);
return new BigDecimal(nextDouble);
}
public void destroy(@Disposes BigDecimal value) {
System.out.println("We don't need this number anymore: " + value);
}
}
2. Create the app class
Steps
- Create a class called
AppNumberin theexpert.os.labs.persistence.cidpackage -
Add a main method
-
Set up a try-with-resources block, inside the
mainmethod, to manage the Jakarta EESeContainerthat is responsible for dependency injection and managing resources -
Obtain the value of the
BigDecimalthrough the container instance - Printout the value
- Run the
main()method
Expected results
-
The following output
Note
The
destroy()method is used as a disposer method forBigDecimalinstances. It takes a parameter of typeBigDecimalannotated with@Disposes. When an instance ofBigDecimalis no longer needed, the CDI container will automatically call this method to perform cleanup or logging. In this case, it prints a message indicating that the number is no longer needed.In summary, this code defines an application-scoped CDI bean (
NumberProducer) that produces randomBigDecimalvalues using a producer method. It also includes a disposer method to handle the cleanup ofBigDecimalinstances when they are no longer needed within the CDI context.
Solution
Click to see...
import jakarta.enterprise.inject.se.SeContainer;
import jakarta.enterprise.inject.se.SeContainerInitializer;
import java.math.BigDecimal;
public class AppNumber {
public static void main(String[] args) {
try (SeContainer container = SeContainerInitializer.newInstance().initialize()) {
BigDecimal value = container.select(BigDecimal.class).get();
System.out.println("Value = " + value);
}
}
}