1. Overview
1.概述
CDI (Contexts and Dependency Injection) is the standard dependency injection framework of the Jakarta EE platform.
CDI(上下文和依赖注入)是 Jakarta EE 平台的标准依赖注入框架。
In this tutorial, we’ll take a look at CDI 2.0 and how it builds upon the powerful, type-safe injection mechanism of CDI 1.x by adding an improved, full-featured event notification model.
在本教程中,我们将了解CDI 2.0,以及它如何在CDI 1.x的强大、类型安全的注入机制基础上,添加一个改进的、全功能的事件通知模型。
2. The Maven Dependencies
2.Maven的依赖性
To get started, we’ll build a simple Maven project.
为了开始,我们将建立一个简单的Maven项目。
We need a CDI 2.0-compliant container, and Weld, the reference implementation of CDI, is a good fit:
我们需要一个符合CDI 2.0标准的容器,而CDI的参考实现Weld则很适合:。
<dependencies>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>3.0.5.Final</version>
</dependency>
</dependencies>
As usual, we can pull the latest versions of cdi-api and weld-se-core from Maven Central.
像往常一样,我们可以从Maven Central拉取最新版本的cdi-api和weld-se-core。
3. Observing and Handling Custom Events
3.观察和处理自定义事件
Simply put, the CDI 2.0 event notification model is a classic implementation of the Observer pattern, based on the @Observes method-parameter annotation. Hence, it allows us to easily define observer methods, which can be automatically called in response to one or more events.
简单地说,CDI 2.0事件通知模型是Observer模式的经典实现,基于@Observes方法-参数注解。因此,它允许我们轻松地定义观察者方法,这些方法可以在响应一个或多个事件时被自动调用。
For instance, we could define one or more beans, which would trigger one or more specific events, while other beans would be notified about the events and would react accordingly.
例如,我们可以定义一个或多个Bean,它们将触发一个或多个特定的事件,而其他Bean将被通知这些事件并作出相应的反应。
To demonstrate more clearly how this works, we’ll build a simple example, including a basic service class, a custom event class, and an observer method that reacts to our custom events.
为了更清楚地证明这一点,我们将建立一个简单的例子,包括一个基本的服务类,一个自定义事件类,以及一个对我们的自定义事件做出反应的观察者方法。
3.1. A Basic Service Class
3.1.一个基本的服务类别
Let’s start by creating a simple TextService class:
让我们从创建一个简单的TextService类开始。
public class TextService {
public String parseText(String text) {
return text.toUpperCase();
}
}
3.2. A Custom Event Class
3.2.一个自定义的事件类
Next, let’s define a sample event class, which takes a String argument in its constructor:
接下来,让我们定义一个示例事件类,它的构造函数中需要一个String参数。
public class ExampleEvent {
private final String eventMessage;
public ExampleEvent(String eventMessage) {
this.eventMessage = eventMessage;
}
// getter
}
3.3. Defining an Observer Method With the @Observes Annotation
3.3.用@Observes注解定义一个观察者方法
Now that we’ve defined our service and event classes, let’s use the @Observes annotation to create an observer method for our ExampleEvent class:
现在我们已经定义了我们的服务和事件类,让我们使用@Observes注解来为我们的ExampleEvent类创建一个观察者方法。
public class ExampleEventObserver {
public String onEvent(@Observes ExampleEvent event, TextService textService) {
return textService.parseText(event.getEventMessage());
}
}
While at first sight, the implementation of the onEvent() method looks fairly trivial, it actually encapsulates a lot of functionality through the @Observes annotation.
虽然乍一看, onEvent()方法的实现看起来相当微不足道,但它实际上通过@Observes注解封装了很多功能。
As we can see, the onEvent() method is an event handler that takes ExampleEvent and TextService objects as arguments.
我们可以看到,onEvent()方法是一个事件处理程序,它接收ExampleEvent和TextService对象作为参数。
Let’s keep in mind that all the arguments specified after the @Observes annotation are standard injection points. As a result, CDI will create fully-initialized instances for us and inject them into the observer method.
让我们记住,所有在@Observes注解后指定的参数都是标准的注入点。因此,CDI将为我们创建完全初始化的实例,并将其注入观察者方法中。
3.4. Initializing Our CDI 2.0 Container
3.4.初始化我们的CDI 2.0容器
At this point, we’ve created our service and event classes, and we’ve defined a simple observer method to react to our events. But how do we instruct CDI to inject these instances at runtime?
在这一点上,我们已经创建了我们的服务和事件类,并且定义了一个简单的观察者方法来对我们的事件做出反应。但是我们如何指示CDI在运行时注入这些实例呢?
Here’s where the event notification model shows its functionality to its fullest. We simply initialize the new SeContainer implementation and fire one or more events through the fireEvent() method:
这里是事件通知模型最充分展示其功能的地方。我们简单地初始化新的SeContainer实现,并通过fireEvent()方法触发一个或多个事件。
SeContainerInitializer containerInitializer = SeContainerInitializer.newInstance();
try (SeContainer container = containerInitializer.initialize()) {
container.getBeanManager().fireEvent(new ExampleEvent("Welcome to Baeldung!"));
}
Note that we’re using the SeContainerInitializer and SeContainer objects because we’re using CDI in a Java SE environment, rather than in Jakarta EE.
注意,我们使用SeContainerInitializer和SeContainer对象,因为我们是在Java SE环境中使用CDI,而不是在Jakarta EE中。
All the attached observer methods will be notified when the ExampleEvent is fired by propagating the event itself.
当ExampleEvent被触发时,所有附加的观察者方法将通过传播事件本身而被通知。
Since all the objects passed as arguments after the @Observes annotation will be fully initialized, CDI will take care of wiring up the whole TextService object graph for us, before injecting it into the onEvent() method.
由于在@Observes注解之后作为参数传递的所有对象将被完全初始化,CDI将在将其注入onEvent()方法之前为我们处理好整个TextService对象图的布线。
In a nutshell, we have the benefits of a type-safe IoC container, along with a feature-rich event notification model.
简而言之,我们拥有类型安全的IoC容器的优势,以及功能丰富的事件通知模型。
4. The ContainerInitialized Event
4.ContainerInitialized事件
In the previous example, we used a custom event to pass an event to an observer method and get a fully-initialized TextService object.
在前面的例子中,我们使用了一个自定义事件,将一个事件传递给一个观察者方法,并得到一个完全初始化的TextService对象。
Of course, this is useful when we really need to propagate one or more events across multiple points of our application.
当然,当我们真的需要在应用程序的多个点上传播一个或多个事件时,这很有用。
Sometimes, we simply need to get a bunch of fully-initialized objects that are ready to be used within our application classes, without having to go through the implementation of additional events.
有时候,我们只需要获得一堆完全初始化的对象,这些对象可以在我们的应用类中使用,而不需要通过额外事件的实现。
To this end, CDI 2.0 provides the ContainerInitialized event class, which is automatically fired when the Weld container is initialized.
为此,CDI 2.0提供了ContainerInitialized事件类,它在Weld容器被初始化时自动触发。
Let’s take a look at how we can use the ContainerInitialized event for transferring control to the ExampleEventObserver class:
让我们来看看我们如何使用ContainerInitialized事件来将控制权转移到ExampleEventObserver类。
public class ExampleEventObserver {
public String onEvent(@Observes ContainerInitialized event, TextService textService) {
return textService.parseText(event.getEventMessage());
}
}
And keep in mind that the ContainerInitialized event class is Weld-specific. So, we’ll need to refactor our observer methods if we use a different CDI implementation.
请记住,ContainerInitialized事件类是Weld特有的。所以,如果我们使用不同的CDI实现,就需要重构我们的观察者方法。
5. Conditional Observer Methods
5.有条件的观察者方法
In its current implementation, our ExampleEventObserver class defines by default an unconditional observer method. This means that the observer method will always be notified of the supplied event, regardless of whether or not an instance of the class exists in the current context.
在当前的实现中,我们的ExampleEventObserver类默认定义了一个无条件的观察者方法。这意味着观察者方法将始终被通知所提供的事件,而不管当前上下文中是否存在该类的实例。
Likewise, we can define a conditional observer method by specifying notifyObserver=IF_EXISTS as an argument to the @Observes annotation:
同样,我们可以通过指定notifyObserver=IF_EXISTS作为@Observes注解的参数来定义一个条件观察者方法。
public String onEvent(@Observes(notifyObserver=IF_EXISTS) ExampleEvent event, TextService textService) {
return textService.parseText(event.getEventMessage());
}
When we use a conditional observer method, the method will be notified of the matching event only if an instance of the class that defines the observer method exists in the current context.
当我们使用条件观察者方法时,只有在当前上下文中存在定义观察者方法的类的实例时,该方法才会被通知到匹配的事件。
6. Transactional Observer Methods
6.事务性观察者方法
We can also fire events within a transaction, such as a database update or removal operation. To do so, we can define transactional observer methods by adding the during argument to the @Observes annotation.
我们也可以在事务中触发事件,例如数据库更新或删除操作。为此,我们可以通过在@Observes注解中添加during参数来定义事务性观察者方法。
Each possible value of the during argument corresponds to a particular phase of a transaction:
during参数的每个可能值都对应于交易的一个特定阶段。
- BEFORE_COMPLETION
- AFTER_COMPLETION
- AFTER_SUCCESS
- AFTER_FAILURE
If we fire the ExampleEvent event within a transaction, we need to refactor the onEvent() method accordingly to handle the event during the required phase:
如果我们在一个事务中触发ExampleEvent事件,我们需要相应地重构onEvent()方法,以便在所需阶段处理该事件。
public String onEvent(@Observes(during=AFTER_COMPLETION) ExampleEvent event, TextService textService) {
return textService.parseText(event.getEventMessage());
}
A transactional observer method will be notified of the supplied event only in the matching phase of a given transaction.
交易观察者方法将只在给定交易的匹配阶段被通知所提供的事件。
7. Observer Methods Ordering
7.观察者方法排序
Another nice improvement included in CDI 2.0’s event notification model is the ability for setting up an ordering or priority for calling observers of a given event.
CDI 2.0的事件通知模型中包含的另一个很好的改进是能够为调用一个给定事件的观察者设置一个顺序或优先级。
We can easily define the order in which the observer methods will be called by specifying the @Priority annotation after @Observes.
我们可以通过在@Observes.后面指定@Priority注解来轻松定义观察者方法被调用的顺序。
To understand how this feature works, let’s define another observer method, aside from the one that ExampleEventObserver implements:
为了理解这个功能是如何工作的,除了ExampleEventObserver实现的方法外,让我们定义另一个观察者方法。
public class AnotherExampleEventObserver {
public String onEvent(@Observes ExampleEvent event) {
return event.getEventMessage();
}
}
In this case, both observer methods by default will have the same priority. Thus, the order in which CDI will invoke them is simply unpredictable.
在这种情况下,两个观察者方法在默认情况下将具有相同的优先级。因此,CDI调用它们的顺序是根本无法预测的。
We can easily fix this by assigning to each method an invocation priority through the @Priority annotation:
我们可以通过@Priority注解给每个方法分配一个调用优先级来轻松解决这个问题。
public String onEvent(@Observes @Priority(1) ExampleEvent event, TextService textService) {
// ... implementation
}
public String onEvent(@Observes @Priority(2) ExampleEvent event) {
// ... implementation
}
Priority levels follow a natural ordering. Therefore, CDI will call first the observer method with a priority level of 1 and will invoke second the method with a priority level of 2.
优先级遵循自然排序。因此,CDI将首先调用优先级为1的观察者方法,其次调用优先级为2的方法。
Likewise, if we use the same priority level across two or more methods, the order is again undefined.
同样地,如果我们在两个或更多的方法中使用相同的优先级,那么顺序也是未定义的。
8. Asynchronous Events
8.异步事件
In all the examples that we’ve learned so far, we fired events synchronously. However, CDI 2.0 allows us to easily fire asynchronous events as well. Asynchronous observer methods can then handle these asynchronous events in different threads.
在我们到目前为止所学的所有例子中,我们都是同步地触发事件。然而,CDI 2.0允许我们也可以轻松地触发异步事件。然后,异步观察者方法可以在不同线程中处理这些异步事件。
We can fire an event asynchronously with the fireAsync() method:
我们可以用fireAsync()方法异步地触发一个事件。
public class ExampleEventSource {
@Inject
Event<ExampleEvent> exampleEvent;
public void fireEvent() {
exampleEvent.fireAsync(new ExampleEvent("Welcome to Baeldung!"));
}
}
Beans fire up events, which are implementations of the Event interface. Therefore, we can inject them as any other conventional bean.
Bean发射事件,它是Event接口的实现。因此,我们可以像其他常规Bean一样注入它们。
To handle our asynchronous event, we need to define one or more asynchronous observer methods with the @ObservesAsync annotation:
为了处理我们的异步事件,我们需要用@ObservesAsync注解定义一个或多个异步观察者方法。
public class AsynchronousExampleEventObserver {
public void onEvent(@ObservesAsync ExampleEvent event) {
// ... implementation
}
}
9. Conclusion
9.结论
In this article, we learned how to get started using the improved event notification model bundled with CDI 2.0.
在这篇文章中,我们学习了如何开始使用CDI 2.0捆绑的改进的事件通知模型,。
As usual, all the code samples shown in this tutorial are available over on GitHub.
像往常一样,本教程中显示的所有代码样本都可以在GitHub上获得。