Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Jakarta EE Cookbook

You're reading from   Jakarta EE Cookbook Practical recipes for enterprise Java developers to deliver large scale applications with Jakarta EE

Arrow left icon
Product type Paperback
Published in May 2020
Publisher Packt
ISBN-13 9781838642884
Length 380 pages
Edition 2nd Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Elder Moraes Elder Moraes
Author Profile Icon Elder Moraes
Elder Moraes
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. New Features and Improvements 2. Server-Side Development FREE CHAPTER 3. Building Powerful Services with JSON and RESTful Features 4. Web and Client-Server Communication 5. Security of the Enterprise Architecture 6. Reducing Coding Effort by Relying on Standards 7. Deploying and Managing Applications on Major Jakarta EE Servers 8. Building Lightweight Solutions Using Microservices 9. Using Multithreading on Enterprise Context 10. Using Event-Driven Programming to Build Reactive Applications 11. Rising to the Cloud - Jakarta EE, Containers, and Cloud Computing 12. Other Books You May Enjoy Appendix - The Power of Sharing Knowledge

Running your first Jakarta CDI 2.0 code

Jakarta Contexts and Dependency Injection (CDI) is certainly one of the most important APIs for the Jakarta EE platform. In version 2.0, it also works with Java SE.

Nowadays, CDI has an impact on many other APIs in the Jakarta EE platform as said in an interview for Java EE 8 – The Next Frontier project:

"If there was CDI by the time we created JSF, it would be made completely different."
– Ed Burns, JSF Spec Lead

There are a lot of new features in CDI 2.0. This recipe will cover observer ordering to give you a quick start.

Getting ready

We need to add the right CDI 2.0 dependency to your project. To make things easier at this point, we are going to use CDI SE, the dependency that allows you to use CDI without a Jakarta EE server:

<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-shaded</artifactId>
<version>3.1.0.Final</version>
</dependency>

How to do it...

This recipe will show you one of the main features introduced by CDI 2.0: ordered observers. Now, you can turn the observer's job into something predictable:

  1. First, let's create an event to be observed:
public class MyEvent {

private final String value;

public MyEvent(String value){
this.value = value;
}

public String getValue(){
return value;
}
}
  1. Now, we build our observers and the server that will fire them:
public class OrderedObserver {

public static void main(String[] args){
try(SeContainer container =
SeContainerInitializer.newInstance().initialize()){
container
.getBeanManager()
.fireEvent(new MyEvent("event: " +
System.currentTimeMillis()));
}
}

public void thisEventBefore(
@Observes @Priority(Interceptor.Priority
.APPLICATION - 200)
MyEvent event){

System.out.println("thisEventBefore: " + event.getValue());
}

public void thisEventAfter(
@Observes @Priority(Interceptor.Priority
.APPLICATION + 200)
MyEvent event){

System.out.println("thisEventAfter: " + event.getValue());
}
}

  1. Also, don't forget to add the beans.xml file to the META-INF folder:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
  1. Once you run it, you should see a result like this:
INFO: WELD-ENV-002003: Weld SE container 
353db40d-e670-431d-b7be-4275b1813782 initialized

thisEventBefore: event -> 1501818268764
thisEventAfter: event -> 1501818268764

Now, let's see how this works.

How it works...

First, we are building a server to manage our event and observers:

public static void main(String[] args){
try(SeContainer container =
SeContainerInitializer.newInstance().initialize()){
container
.getBeanManager()
.fireEvent(new ExampleEvent("event: "
+ System.currentTimeMillis()));
}
}

This will give us all of the resources needed to run the recipe as if it were a Jakarta EE server.

Then, we build an observer, as follows:

public void thisEventBefore(
@Observes @Priority(Interceptor.Priority.APPLICATION - 200)
MyEvent event){

System.out.println("thisEventBefore: " + event.getValue());
}

So, we have three important topics:

  • @Observes: This annotation is used to tell the server that it needs to watch the events fired with MyEvent.
  • @Priority: This annotation informs in which priority order this observer needs to run; it receives an int parameter, and the execution order is ascendant.
  • MyEvent event: This is the event being observed.

In the thisEventBefore method and thisEventAfter, we only changed the @Priority value and the server took care of running it in the right order.

There's more...

The behavior would be exactly the same in a Jakarta EE 8 server. You just wouldn't need SeContainerInitializer and would need to change the dependencies to the following:

        <dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>8.0.0</version>
</dependency>

See also

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime