When Weld is in the process of delivering events to observers during our call to Event.fire()
, it will automatically instantiate the bean that defines the observer method to be called if there isn't currently an instance of that bean present within the current context.
For most cases that is perfectly fine, but there may be situations where that default behavior is unwanted. Thankfully, CDI allows us to define a conditional observer, such that the bean will only observe events if it's already present within the current context.
We can specify a conditional observer by setting a value for the notifyObserver
member of @Observes
.
public void refreshOnBookRemoval (@Observes( notifyObserver = IF_EXISTS ) @Removed Book bk) { ... }
Note
Any bean in the scope of @Dependent
is not allowed to be a conditional observer, as there would be no way for the bean to be instantiated and observe the event.
The possible values for notifyObserver
are defined in javax.enterprise.event...