Listening To Transaction Progress With CDI 📎
CDI Events are transactional. You can easily broadcast any object you like as a message:
@Stateless
public class TXTracker {
@Inject
Event<String> txListeners;
@Resource
SessionContext sc;
public void success(){
txListeners.fire("[Event] succcess");
}
public void failure(){
txListeners.fire("[Event] rollback");
sc.setRollbackOnly();
}
}
A fully decoupled listener is going to receive all the events synchronously. In addition you can also specify the transaction phase in which the event is going to be delivered. Effectively the event's delivery is delayed, but the sender has still to wait until the completion of all listeners:
public class TXStatusListener {
public void onInProgress(@Observes String msg){
System.out.println("In progress: " + msg);
}
public void onSuccess(@Observes(during= TransactionPhase.AFTER_SUCCESS) String msg){
System.out.println("After success: " + msg);
}
public void onFailure(@Observes(during= TransactionPhase.AFTER_FAILURE) String msg){
System.out.println("After failure: " + msg);
}
}
[See also an in-depth discussion in the "Real World Java EE Patterns--Rethinking Best Practices" book (Second Iteration, "Green Book"), page 209 in, chapter "Transaction Progress Listener"]
The project transaction-listener was checked in into https://kenai.com/projects/javaee-patterns/sources/hg/show/transaction-listener
See you at Java EE Workshops at MUC Airport!