- Java EE 8 and Angular
- Prashant Padmanabhan
- 283字
- 2021-07-02 19:22:34
Enhancing events
CDI 1.1 had an event notification model, which has become popular among developers as it helps with the decoupling of code, following the observer pattern. Version 2.0 builds on this model and adds more enhancements, such as asynchronous event processing along with the ordering of events. To observe an event, the bean simply defines a method that has the @Observes annotation, and a parameter type that is used by CDI to identify the event type (class type), which should be passed to this method:
public void process(@Observes Task task) { }
Further restrictions on which events are passed to the observer method can be applied by using qualifiers at the injection point. Interestingly, the observer can work with generic types as well. Given the following two observers, the container will invoke the appropriate method based on the parameterized type of the event:
public void processTaskList(@Observes List<Task> taskList) { }
public void processTaskIds(@Observes List<Integer> taskIdList) { }
The raising of events is done using the Event interface methods for firing either synchronous or asynchronous events with a payload. The order in which the observers are called is not defined, unless the ordered events approach mentioned later is followed. It’s also possible to change the data in an observer, since the data (or payload) passed is not mandated to be immutable. Here's the relevant portion of the code snippet used for firing an event:
@Inject Event<Task> event;
public void doSomething() {
event.fire( new Task() );
}
The corresponding observer would be as follows:
public void handle(@Observes Task task) {
// can update the task instance
}
With CDI 2 offering asynchronous events and ordered events, let's explore each in more detail.
- 多媒體CAI課件設計與制作導論(第二版)
- Spring Cloud Alibaba核心技術與實戰案例
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- ASP.NET Core 5.0開發入門與實戰
- 大學計算機基礎實驗教程
- Go語言高效編程:原理、可觀測性與優化
- 批調度與網絡問題的組合算法
- Spring MVC+MyBatis開發從入門到項目實踐(超值版)
- Illustrator CS6設計與應用任務教程
- TypeScript全棧開發
- INSTANT Premium Drupal Themes
- Python計算機視覺與深度學習實戰
- 秒懂算法:用常識解讀數據結構與算法
- JavaScript程序設計基礎教程(慕課版)
- Java EE框架開發技術與案例教程