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-ee
project and navigate to thesrc/main/java
- Create a package named
producer
in theexpert.os.labs.persistence.cid
package - Create a class called
NumberProducer
in theexpert.os.labs.persistence.cid.producer
package - Annotate it with the
@ApplicationScoped
from thejakarta.enterprise.context
package - Add a producer method, annotating it with
@Produces
from thejakarta.enterprise.inject
package and generate a randomBigDecimal
value within the range [1, 100] using theThreadLocalRandom
and return it - Add a disposer method named
destroy()
to remove the value from the class where it has avalue
parameter annotated with@Disposes
from thejakarta.enterprise.inject
package
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
AppNumber
in theexpert.os.labs.persistence.cid
package -
Add a main method
-
Set up a try-with-resources block, inside the
main
method, to manage the Jakarta EESeContainer
that is responsible for dependency injection and managing resources -
Obtain the value of the
BigDecimal
through 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 forBigDecimal
instances. It takes a parameter of typeBigDecimal
annotated with@Disposes
. When an instance ofBigDecimal
is 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 randomBigDecimal
values using a producer method. It also includes a disposer method to handle the cleanup ofBigDecimal
instances 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);
}
}
}