官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 安国市| 牟定县| 新丰县| 大石桥市| 巧家县| 漾濞| 崇明县| 夹江县| 靖州| 宁蒗| 布尔津县| 方山县| 沙田区| 新宾| 成安县| 五峰| 金川县| 酒泉市| 盘锦市| 清徐县| 镇沅| 且末县| 酒泉市| 南宁市| 曲沃县| 松潘县| 孟连| 天长市| 九龙城区| 曲阜市| 鸡泽县| 彭泽县| 六枝特区| 泰宁县| 都江堰市| 潮安县| 综艺| 郯城县| 广西| 阳朔县| 当雄县|