The answer of this question describes that it is possible to sort CDI events with the @Priority annotation.
Execution order of different CDI Events in same transaction
Since CDI 2.0 (check here, Chapter 10.5.2), you may define an order using the @Priority annotation and specifying a number as its value. Observers with smaller priority values are called first and observers with no @Priority annotation gets de default priority (Priority.APPLICATION + 500). As with CDI 1.2, observers with same priority does not have any previously defined order and may be called by CDI container in any order.
CDI 2.0 observer ordering does not apply to asynchronous observer methods (per spec), as it's expected that observer methods get called as soon as it is possible and in different contexts. If you need some kind of ordering in you use case, you should make your asynchronous observer trigger the next event, instead of calling it from your "main" method.
So even if i fire Two different Event-Objects the order is not specified? – Noixes Jul 22 '20 at 6:45
Yes. Unless you are using CDI 2 and defining different priorities, the order is unspecified. You must realize that you may "discover" the order of a given implementation in such cases, but it is not recommended to rely on it because a future version of the same implementation may change it without colliding with the spec. –
But it doesn't work in my example:
@Stateless
public class EventTest {
@Inject
@QualifierA
private Event<String> eventA;
@Inject
@QualifierB
private Event<String> eventB;
@Test
public void test() throws VerarbeitungsException {
eventB.fire("B");
eventA.fire("A");
}
public void observerA(@Observes(during = TransactionPhase.AFTER_SUCCESS) @Priority(value = 1) @QualifierA String xml) {
send(xml);
}
public void observerB(@Observes(during = TransactionPhase.AFTER_SUCCESS) @Priority(value = 2) @QualifierB String xml) {
send(xml);
}
private void send(String xml){
System.out.println(xml);
}
}
In my testclass I fire event B and then A. The test log show B/A but I woud expact A/B as defined with @Priority. Im using WildFly14 with CDI 2.0. Does sorting of Events only work for observer for the same event/qualifier?
The ordering is between observers of the same event. But you defined two events, with different qualifiers.
To properly test the priority you should fire only one event, and set two observers for that event.
For example:
@Stateless
public class EventTest {
@Inject
@QualifierA
private Event<String> eventA;
@Test
public void test() throws VerarbeitungsException {
eventA.fire("A");
}
public void observerA(@Observes(during = TransactionPhase.AFTER_SUCCESS) @Priority(value = 1) @QualifierA String xml) {
send("A: " + xml);
}
public void observerB(@Observes(during = TransactionPhase.AFTER_SUCCESS) @Priority(value = 2) @QualifierB String xml) {
send("B: " + xml);
}
private void send(String xml){
System.out.println(xml);
}
}